I3306 Chapter5
I3306 Chapter5
References
http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/toc.htm
Chapter Outline
• Overview of PL/SQL
• PL/SQL Basic Syntax
• Data Types, Variables and Operators
• Control Statements
• Subprograms: Procedures, Functions
• Cursors
• Records
• Error-Handling, Exceptions
• Triggers
• Packages
• Collections
• What is PL/SQL
• Main Features of PL/SQL
• Block
• Identifiers
• Delimiters
• Comments
Output
Hello, World!
PL/SQL procedure successfully completed.
DECLARE
-- variable declaration
message varchar2(20):= 'Hello, World!';
BEGIN
/*
* PL/SQL executable statement(s)
*/
dbms_output.put_line(message);
END;
Dr Michel Nabaa / PL/SQL 13
PL/SQL Data Types
Scalar : Single values with no internal components, such as
a NUMBER, DATE, or BOOLEAN.
– Unconstrained Subtypes
An unconstrained subtype has the same set of values as its base type, so it is
only another name for the base type
subtype "double precision" is float
– Constrained Subtypes
A constrained subtype has only a subset of the values of its base type.
DECLARE
v_sales number(10, 2);
c_pi CONSTANT double precision := 3.1415;
v_name varchar2(25);
v_greetings varchar2(20) DEFAULT 'Have a Good Day';
• Variable Scope
PL/SQL allows the nesting of blocks
Local variables − Variables declared in an inner block and not accessible to outer
blocks.
Global variables − Variables declared in the outermost block or a package.
Examples
v_emp_lname employees.last_name%TYPE;
v_balance NUMBER(7,2);
v_min_balance v_balance%TYPE := 1000;
• Arithmetic operators +, -. *, /, **
• Relational operators =, != or <> or ~=, >, <, >=, <=
• Comparison operators LIKE, BETWEEN, IN, IS NULL
• Logical operators AND, OR, NOT
• String functions and operators :
CONCAT(x, y); or || Concatenates the strings x and y and returns the appended
string.
INITCAP(x); Converts initial letter of words in x to uppercase and
returns that string.
INSTR(x, find_string [, start] [, occurrence]); Searches for find_string in x and returns the position at
which the specified occurrence occurs.
INSTRB(x, find_string [, start] [, occurrence]); Returns the location of the first byte of a specified
occurrence of a string within another string.
LENGTH(x); Returns the number of characters in x.
NANVL(x, value); Returns value if x matches the NaN special value (not a
number), otherwise x is returned.
Dr Michel Nabaa PL/SQL 23
PL/SQL String functions and operators(2)
NLS_LOWER(x) ; Same as the LOWER function except that it can use a different
sort method as specified by NLSSORT.
NLS_UPPER(x); Same as the UPPER function except that it can use a different
sort method as specified by NLSSORT.
NLSSORT(x); Changes the method of sorting the characters. Must be specified
before any NLS function; otherwise, the default sort will be
used.
NVL(x, value); Returns value if x is null; otherwise, x is returned.
NVL2(x, value1, value2); Returns value1 if x is not null; if x is null, value2 is returned.
REPLACE(x, search_string, replace_string); Searches x for search_string and replaces it with replace_string.
BEGIN
SELECT first_name, last_name, salary INTO v_first_name, v_last_name, v_salary
FROM Employees
WHERE employee_id = v_id;
DBMS_OUTPUT.PUT_LINE ('Employee ' ||v_first_name || v_last_name || ' earns ' ||
v_salary);
END;
DECLARE
• Synthax
FOR loop_index IN cursor_name
LOOP
Statements …………
END LOOP;
IF THEN
IF THEN ELSE
IF THEN ELSIF
BEGIN
p(55000);
p(40000);
p(30000);
END;
Result
Very Good
Dr Michel Nabaa PL/SQL 48
LOOP Statements
A loop statement allows us to execute a statement or
group of statements multiple times.
• Basic LOOP
• WHILE LOOP
• FOR LOOP
• Nested Loops
• The label should be enclosed by double angle brackets (<< and >>)
and appear at the beginning of the LOOP statement, it can also
appear at the end of the LOOP statement and in the EXIT statement.
• An EXIT statement or an EXIT WHEN statement is required to
break the loop.
PL/SQL procedure
successfully completed.
Dr Michel Nabaa PL/SQL 54
FOR LOOP Statement
FOR counter IN initial_value .. final_value LOOP
sequence_of_statements;
END LOOP;
Result
DECLARE value of v_n: 10
v_n number(2); value of v_n: 11
BEGIN value of v_n: 12
FOR v_n in 10 .. 20 LOOP value of v_n: 13
DBMS_OUTPUT.PUT_LINE('value of v_n: ' || value of v_n: 14
v_n); value of v_n: 15
END LOOP; value of v_n: 16
END; value of v_n: 17
/ value of v_n: 18
value of v_n: 19
value of v_n: 20
PL/SQL procedure
successfully completed.
Dr Michel Nabaa PL/SQL 55
Reverse FOR LOOP Statement
FOR counter IN REVERSE initial_value .. final_value
LOOP
sequence_of_statements;
END LOOP;
Result
DECLARE value of v_n: 20
v_n number(2) ; value of v_n: 19
value of v_n: 18
BEGIN
value of v_n: 17
FOR v_n IN REVERSE 10 .. 20 LOOP value of v_n: 16
DBMS_OUTPUT.PUT_LINE('value of v_n: ' || value of v_n: 15
v_n); value of v_n: 14
END LOOP; value of v_n: 13
END; value of v_n: 12
/ value of v_n: 11
value of v_n: 10
record-name type_name;
• Like anonymous PL/SQL blocks, the named blocks will also have
the following three parts :
– Declarative part
– Executable part
– Error handling or Exception part
BEGIN
greetings;
END;
/
• A standalone procedure is deleted with the DROP PROCEDURE
statement.
Result
Minimum of (23, 45) : 23
PL/SQL procedure successfully completed.
Dr Michel Nabaa PL/SQL 77
Parameter Modes in PL/SQL
Subprograms (4)
CREATE OR REPLACE PROCEDURE squareNum(p_x IN OUT number) IS
BEGIN
p_x := p_x * p_x;
END;
From a separated SQL file, we add the following code to execute the procedure.
DECLARE
v1 number;
BEGIN
v1:= 23;
squareNum(v1);
DBMS_OUTPUT.PUT_LINE(' Square of (23): ' || v1);
END;
Result
Square of (23): 529
RETURN clause specifies the data type of the value returned from the function.
AS keyword is used instead of the IS keyword for creating a standalone function.
From a separated SQL file, we add the following code to execute the
procedure.
Declare
v_nbemp number(3) := 0;
BEGIN
v_nbemp := totalemployees();
DBMS_OUTPUT.PUT_LINE('Total no. of employees: ' || v_nbemp);
END;
Dr Michel Nabaa PL/SQL 80
Notations used for Passing Parameters
(1)
Actual parameters can be passed in three ways :
• Positional Notation :
– In positional notation, the first actual parameter is substituted
for the first formal parameter; the second actual parameter is
substituted for the second formal parameter, and so on.
findMin( v1, v2, v3 );
• Named Notation :
– the actual parameter is associated with the formal parameter
using the arrow symbol ( => ).
findMin(p_x => v1, p_y => v2, p_z => v3);
• Mixed Notation
– you can mix both notations in procedure call; however, the
positional notation should precede the named notation
findMin(v1, v2, p_z => v3);
Dr Michel Nabaa PL/SQL 81
Notations used for Passing Parameters
DECLARE (2)
v_emp_num NUMBER(6) := 100;
Result
v_bonus NUMBER(6) := 50;
v_salary employees.salary%type; Employee salary : 24400
PROCEDURE raise_salary ( p_emp_id NUMBER, p_amount NUMBER ) Employee salary : 24450
IS
BEGIN Employee salary : 24500
UPDATE employees Employee salary : 24550
SET salary = salary + p_amount Employee salary : 24600
WHERE employee_id = p_emp_id;
END raise_salary;
BEGIN
----- Equivalent invocations:
SELECT salary INTO v_salary FROM employees WHERE employee_id = v_emp_num;
DBMS_OUTPUT.PUT_LINE('employee salary:'|| v_salary);
raise_salary(v_emp_num, v_bonus);
SELECT salary INTO v_salary FROM employees WHERE employee_id = v_emp_num;
DBMS_OUTPUT.PUT_LINE('employee salary:'|| v_salary); -- positional notation
raise_salary(p_amount => v_bonus, p_emp_id => v_emp_num);
SELECT salary INTO v_salary FROM employees WHERE employee_id = v_emp_num;
dbms_output.put_line('employee salary:'|| v_salary); -- named notation
raise_salary(p_emp_id => v_emp_num, p_amount => v_bonus);
SELECT salary INTO v_salary FROM employees WHERE employee_id = v_emp_num;
DBMS_OUTPUT.PUT_LINE('employee salary:'|| v_salary); -- named notation
raise_salary(v_emp_num, p_amount => v_bonus);
SELECT salary INTO v_salary FROM employees WHERE employee_id = v_emp_num;
DBMS_OUTPUT.PUT_LINE('employee salary:'|| v_salary); -- mixed notation
END;
/
ACCESS_INTO_NULL 06530 -6530 It is raised when a null object is automatically assigned a value.
ACCESS_INTO_NULL 06530 -6530 It is raised when a null object is automatically assigned a value.
ZERO_DIVIDE 01476 1476 It is raised when an attempt is made to divide a number by zero.
Enable a Trigger
ALTER TRIGGER trigger_name ENABLE;
Drop a trigger
DROP TRIGGER trigger_name;
Dr Michel Nabaa PL/SQL 94
Benefits of Triggers
Triggers can be written for the following purposes :
Package created.
package_name.element_name;