Spis treści 1 Introduction

Table of Contents
Spis treści
1 Introduction
1
2 PL/SQL - fundamentals
2.1 Variables and Constants
2.2 Operators . . . . . . . .
2.3 SQL in PL/SQL . . . . .
2.4 Control structures . . . .
1
2
5
6
7
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
3 Summary
10
4 Resources
10
1
Introduction
PL/SQL
PL/SQL
(ang. Procedural Language/Structured Query Language) - procedural extension of SQL
(based on the ADA language). Allows the use of structures such as loops, conditional
statements, variables, and creating procedures, functions, triggers, supporting the concrete
implementation of the database.
It was developed by Oracle Corporation in the early 90’s to enhance the capabilities
of SQL (each distributor provides its solutions (eg. PL/pgSQL in PostgreSQL), which are
similar to the PL/SQL).
Features PL/SQL
• procedural language oriented on data processing
• a compiled language
• supports variables, constants, control structures, exceptions
• has a block structure
• each statement within a block of PL / SQL is followed by a semicolon ”;”
• assignment operator is := ,
• can contain DML and TCL instructions
• can not contain DDL and DCL (session control)
• provides reusable program units
1
2
PL/SQL - fundamentals
PL/SQL blocks
The basic unit PL/SQL is a block, we have:
• anonymous blocks,
• named blocks,
• subprograms.
A PL/SQL block consist of four sections:
• declarative (optional),
• executable section that starts with begin (required),
• exceptional handling (optional),
• ebd; (mandatory)
PL/SQL block structure
[DECLARE
variables; cursors;
user_defined_exceptions;]
BEGIN
SQL_statements;
PL/SQL_statements;
[EXCEPTION
exception_handling;]
END;
Comments
There are two syntaxes that you can use to create a comment:
• a single line: -• many lines: starts with /*, ends with */.
PL/SQL data types
• scalar:
– numeric (BINARY INTEGER, PLS INTEGER, BINARY FLOAT, BINARY DOUBLE,
NUMBER subtypes: DEC, DECIMAL, or NUMERIC, DOUBLE PRECISION
or FLOAT, INT, INTEGER, or SMALLINT, REAL)
– character (CHAR, VARCHAR2, RAW, NCHAR, NVARCHAR2, LONG, LONG
RAW, ROWID, UROWID)
– BOOLEAN
2
– Date and time (DATE, TIMESTAMP, TIMESTAMP WITH TIME ZONE,
TIMESTAMP WITH LOCAL TIME ZONE)
– Interval (INTERVAL YEAR TO MONTH, INTERVAL DAY TO SECOND)
• composite (collections: associative array, nested table, varray; records),
• reference (REF CURSOR, REF object type),
• large object (BFILE, BLOB, CLOB, NCLOB),
• user-defined PL/SQL subtypes.
2.1
Variables and Constants
Use of Variables
• Temporary storage of data
• Manipulation of stored values
• Reusability
Requirements for Variable Names
• Must start with a letter
• Can include letters or numbers
• Can include special characters
• Must contain no more than 30 characters
• Must not include reserved words
Handling Variables
Variables are:
• Declared and optionally initialized in the declarative section
• Used and assigned new values in the executable section
• Passed as parameters to PL/SQL subprograms
• Used to hold the output of a PL/SQL subprogram
Declaring and Initializing
identifier [CONSTANT] datatype [NOT NULL]
[{:= | DEFAULT} expr];
Examples:
DECLARE
v_age
v_gender
v_i
v_sum
c_pi
NUMBER(3);
VARCHAR2(9);
NUMBER(4) NOT NULL := 0;
NUMBER(10) DEFAULT 0;
CONSTANT NUMBER := 3.1415;
3
Declaring and Initializing
DECLARE
v_first_name VARCHAR2(20) := ’Anna’;
v_last_name VARCHAR2(30);
BEGIN
v_last_name := ’Scott’;
DBMS_OUTPUT.PUT_LINE(’My name is ’ || v_first_name
|| ’ ’ || v_last_name);
END;
/
Special characters in strings
• Use additional single quotation mark:
v_string VARCHAR2(20) := ’I’’m learning’;
• Specification of delimiter with q’ notation:
v_string := q’!I’m listening!’;
v_string := q’[I’m bored]’;
• Specification of delimiter with nq’ notation (for NCHAR or NVARCHAR types):
v_nstr NVARCHAR2(20) := nq’<I’m sleeping>’;
v_nstr := nq’{I’m dreaming}’;
%TYPE
%TYPE attribute is used to declare variable according to a database column definition
or another declared variable.
identifier table.column_name%TYPE;
Examples
DECLARE
v_first_name employees.first_name%TYPE;
v_last_name employees.last_name%TYPE;
RECORD
Declaration:
TYPE record_name IS RECORD (
field1 datatype [NOT NULL] [initialization]
[, field2 datatype [NOT NULL] [initialization]
...]
);
variable_name record_name;
Example:
DECLARE
TYPE r_address IS RECORD (
v_street VARCHAR2(30),
v_num
VARCHAR2(4),
v_loc
VARCHAR2(4)
);
vr_address r_address;
4
%ROWTYPE
DECLARE
record_variable table%ROWTYPE;
Example:
DECLARE
vr_employee employees%ROWTYPE;
Bind Variables
• Created in the environment
• Also called host variables
• Created with the VARIABLE keyword
• Used in SQL and PL/SQL
• Accessed even after the PL/SQL block is executed
• Referenced with a preceding colon
Bind Variables
VARIABLE b_salary NUMBER;
BEGIN
:b_salary := 2500;
END;
/
PRINT b_salary
Data Type Convertion
• Implicit conversion
– Characters and numbers
– Characters and dates
• Explicit converstion
– use built-in functions (for example To_char, To_number, To_date, To_timestamp)
– user defined functions
Variable Scope and Visibility
• The scope of a variable is the part of the program in which the variable is declared
and visible
• The visibility of a variable is the portion of the program where the varaiable can be
accessed without using a qualifier outer
5
2.2
Operators
Operators in PL/SQL
The same as in SQL:
• logical (And, OR, NOT)
• arithmetic (+,-,/,*)
• concatenation (||)
• comparison (=,<>,!=,<,<=,>,>=, IS NULL, IS NOT NULL, LIKE, BETWEEN, IN)
• negation (-)
• parentheses
Additional operator for exponentation (**)
2.3
SQL in PL/SQL
SQL in PL/SQL
How to embed SQL within PL/SQL?
Built-in SQL functions
In procedural statements
• we can use built-in SQL single row functions (Upper, Length, Substr, Round,
Last_day, To_char etc.)
• we can not use DECODE and aggregation functions
Sequences
DECLARE
v_id NUMBER;
BEGIN
v_id := emp_seq.NEXTVAL;
END;
/
SQL in PL/SQL
Inside PL/SQL we can use some of SQL statements:
• queries: SELECT with INTO,
• DML: INSERT, UPDATE, DELETE, MERGE,
• TCL: COMMIT, ROLLBACK, SAVEPOINT, SET TRANSACTION, LOCK.
SELECT Statement
SELECT statement must return only one row !!!
The INTO clause is required !!!
The names of database columns take precedence over the names of local
variables !!!
SELECT select_list
INTO {variables_list | record_name}
FROM ...;
6
SELECT example
DECLARE
v_first_name employees.first_name%TYPE;
BEGIN
SELECT first_name INTO v_first_name
FROM employees
WHERE employee_id = 200;
DBMS_OUTPUT.PUT_LINE(’First name is ’
|| v_first_name);
END;
/
SQL in PL/SQL
We don’t have to change syntax of INSERT, UPDATE and DELETE statements, but
we have additionally RETURNING expr INTO variable:
INSERT INTO departments (department_id,
department_name)
VALUES (90, ’Entertainment’)
RETURNING department_id INTO v_id;
We can also use records:
INSERT INTO table VALUES record_variable;
UPDATE table SET ROW = record_variable WHERE cond;
2.4
Control structures
IF
IF condition THEN
statements;
END IF;
IF condition THEN
statemnts1;
ELSE
statements2;
END IF;
IF condition1 THEN
statements1;
ELSIF condition2 THEN
statements2;
...
ELSE
statemnents_n;
END IF;
7
CASE
CASE selector
WHEN expression1 THEN instruction1;
WHEN expression2 THEN instruction2;
...
[ELSE instruction_n];
END CASE;
CASE
WHEN condition1 THEN instruction1;
WHEN condition2 THEN instruction2;
...
[ELSE instruction_n];
END CASE;
Loops
LOOP
instructions;
EXIT [WHEN condition];
END LOOP;
WHILE condition LOOP
instructions;
END LOOP;
FOR counter IN [REVERSE] min..max LOOP
instructions;
END LOOP;
Sugested Use of Loops
• Use the basic loop when the ststaments inside the loop must execute at least once
• Use the WHILE loop if the condition must be evaluated at the start of each iteration
8
• Use a FOR loop if the number of iterations is known
Loop example
DECLARE
v_total SIMPLE_INTEGER := 1;
BEGIN
FOR i IN 1..10 LOOP
v_total := v_total + i;
DBMS_OUTPUT.PUT_LINE(’Value is ’ || v_total);
END LOOP;
END;
/
CONTINUE Statement
• Adds the functionality to begin the next loop iteration
• Gives the ability to transfer control to the next iteration of the loop
• Uses parallel structure and semantics to the EXIT statements
Loop with CONTINUE example
DECLARE
v_total SIMPLE_INTEGER := 0;
v_small SIMPLE_INTEGER := 1;
BEGIN
FOR i IN 1..10 LOOP
v_total := v_small + i;
DBMS_OUTPUT.PUT_LINE(’Total value
|| i || ’ is
CONTINUE WHEN i > 5;
v_small := v_small + i;
DBMS_OUTPUT.PUT_LINE(’Small value
|| i || ’ is
END LOOP;
END;
/
in iteration ’
’ || v_total);
in iteration ’
’ || v_small);
NULL statement
BEGIN
IF condition THEN
instructions;
ELSE
NULL;
END IF;
END;
9
3
Summary
Summary
PL/SQL allows you to use:
• use variables, constants,
• control instructions,
• sequential processing - oriented on data,
• and many others, as in the next lecture ...
4
Resources
Resources
• http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/toc.htm
• M. Lentner, Oracle 9i Kompletny podręcznik użytkownika, PJWSTK - W-wa, 2003
• http://www.ploug.org.pl/showhtml.php?file=szkola/szkola_9/materialy
• http://plsql-tutorial.com/index.htm
• http://www.toadworld.com/platforms/oracle/w/wiki/8243.plsql-obsession.
aspx
10