PLSQL
PLSQL
INTRODUCTION TO PL/SQL
About PL/SQL
PL/SQL:
Stands for Procedural Language extension to SQL Is Oracle Corporations standard data access language for relational databases Seamlessly integrates procedural constructs with SQL
About PL/SQL
PL/SQL
Provides a block structure for executable units of code. Maintenance of code is made easier with such a welldefined structure. Provides procedural constructs such as:
Variables, constants, and data types Control structures such as conditional statements and loops Reusable program units that are written once and executed many times
PL/SQL Engine
Oracle Server
Benefits of PL/SQL
Integration of procedural constructs with SQL Improved performance
SQL 1 SQL 2
Benefits
Modularization
Portability
BENEFITS of PL/SQL
Exception Handling
Integration
With
Oracle tools
BEGIN (mandatory)
SQL statements PL/SQL statements
EXCEPTION (optional)
Actions to perform when exceptions occur
END; (mandatory)
Block Types
Procedure
PROCEDURE name IS BEGIN --statements [EXCEPTION] END;
Function
FUNCTION name RETURN datatype IS BEGIN --statements RETURN value; [EXCEPTION] END;
Anonymous
[DECLARE]
Program Constructs
Tools Constructs Anonymous blocks Application procedures or functions Application packages Application triggers Object types
Database Server Constructs Anonymous blocks Stored procedures or functions Stored packages Database triggers Object types
Click the Run Script button to execute the anonymous block: Run Script (or F5)
2. Use a predefined Oracle package and its procedure in the anonymous block:
DBMS_OUTPUT.PUT_LINE DBMS_OUTPUT.PUT_LINE (' The First Name of the Employee is ' || v_fname) ;
Identifiers
Use of Variables
Variables can be used for:
Temporary storage of data Manipulation of stored values Reusability
SELECT order_id, order_status INTO v_id, v_status FROM
2854
v_id
v_status
Must start with a letter Can include letters or numbers Can include special characters (such as $, _, and #) Must contain no more than 30 characters Must not include reserved words
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
Examples:
Follow consistent naming conventions. Use meaningful identifiers for variables. Initialize variables that are designated as NOT NULL and CONSTANT. Initialize variables with the assignment operator (:=) or the DEFAULT keyword:
v_myName VARCHAR2 (20) := 'John' ; v_myName VARCHAR2( 20) DEFAULT 'John' ;
Declare one identifier per line for better readability and code maintenance.
10
11
%TYPE Attribute
Is prefixed with:
The database table and column name The name of the declared variable
Examples
... v_order_id ... ... v_status v_customerid ... orders.order_id%TYPE ;
NUMBER(2) ; v_status%TYPE := 00 ;
12
Identifiers
13
Commenting Code
Prefix single-line comments with two hyphens (--). Place a block comment between the symbols /* and */.
Example:
DECLARE ... v_annual_sal NUMBER (9,2) ; BEGIN /* Compute the annual salary based on the monthly salary input from the user */ v_annual_sal := monthly_sal * 12 ; --The --The following line displays the annual salary DBMS_OUTPUT.PUT_LINE (v_annual_sal) ; END ; /
14
Functions:
TO_CHAR TO_DATE TO_NUMBER TO_TIMESTAMP
15
-- explicit data type conversion v_date_of_joining DATE := TO_DATE( 'February 02,2000' Month DD, YYYY') ;
Nested Blocks
PL/SQL blocks can be nested.
An executable section (BEGIN END) can contain nested blocks. An exception section can contain nested blocks.
16
Operators in PL/SQL
Logical Same as in SQL Arithmetic Concatenation Parentheses to control order of operations Exponential operator (**)
17
Control Structures
Conditional Control: IF Statements Iterative Control: LOOP and EXIT Statements Sequential Control: GOTO and NULL Statements
18
Control Structures
Conditional Control: IF Statements
To take alternative actions depending on circumstances Three forms of IF statements IF-THEN IF-THEN-ELSE IF-THEN-ELSIF IF-THEN
IF condition THEN sequence_of_statements END IF;
Example:
IF sales > quota THEN compute_bonus(empid); UPDATE payroll SET pay = pay + bonus WHERE emp_id = emp_id; END IF; IF x > y THEN high := x; END IF;
Control Structures
IF-THEN-ELSE IF condition THEN sequence_of_statements1 ELSE sequence_of_statements2 END IF; Example: IF trans_type = 'CR' THEN UPDATE accounts SET balance = balance + credit WHERE ... ELSE UPDATE accounts SET balance = balance - debit WHERE ... END IF;
19
Control Structures
IF-THEN-ELSE IF statements can be nested Example: IF trans_type = 'CR' THEN UPDATE accounts SET balance = balance + credit WHERE ... ELSE IF new_balance >= minimum_balance THEN UPDATE accounts SET balance = balance - debit WHERE ... ELSE RAISE insufficient_funds; END IF; END IF;
Control Structures
IF-THEN-ELSIF
IF condition1 THEN sequence_of_statements1 ELSIF condition2 THEN sequence_of_statements2 ELSE sequence_of_statements3 END IF;
Example:
BEGIN IF sales > 50000 THEN bonus := 1500; ELSIF sales > 35000 THEN bonus := 500; ELSE bonus := 100; END IF; INSERT INTO payroll VALUES (emp_id, bonus, ...); END;
20
Control Structures
Iterative Control: LOOP and EXIT Statements
Loop: The simplest form of LOOP
LOOP sequence_of_statements END LOOP;
Control Structures
EXIT-WHEN EXIT-WHEN statement allows a loop to complete conditionally
LOOP FETCH c1 INTO ... EXIT WHEN c1%NOTFOUND; ... END LOOP; CLOSE c1;
21
Control Structures
Loop Labels
An undeclared identifier enclosed by double angle brackets must appear at the beginning of the LOOP statement
<<outer>> LOOP ... LOOP ... EXIT outer WHEN ... END LOOP; ... END LOOP outer;
Control Structures
WHILE-LOOP
WHILE-LOOP statement associates a condition with a sequence of statements enclosed by the keywords LOOP and END LOOP
WHILE condition LOOP sequence_of_statements END LOOP; WHILE total <= 25000 LOOP ... SELECT basicsal INTO salary FROM emp WHERE ... total := total + salary; END LOOP;
22
Control Structures
FOR-Loop
FOR loops iterate over a specified range of integers
FOR counter IN [REVERSE] lower_bound..higher_bound LOOP sequence_of_statements END LOOP;
Example:
DECLARE x NUMBER := 100; BEGIN FOR i IN 1..10 LOOP IF MOD(i,2) = 0 THEN -- i is even INSERT INTO temp VALUES (i, x,first, 'i is even'); ELSE INSERT INTO temp VALUES (i, x, second,'i is odd'); END IF; x := x + 100; END LOOP; COMMIT; END;
23
Example - 1
Retrieve all the columns of particular employee
Declare V_eno number(4); V_name varchar2(15); V_job varchar2(10); V_mgr number(4); V_hiredate date; V_sal number(7,2); V_comm number(7,2); V_dno number(2); Begin Select * Into v_eno,v_ename,v_job,v_mgr,v_hiredate,v_sal, v_comm,v_dno
48
24
%ROWTYPE
Declare myemp emp%rowtype; Begin select * into myemp . if (myemp.comm is not null) then Structure of emp table is referred and copied to variable myemp. To access the variables use rowtype variable and name of the column. i.e.,myemp.comm
49
Record Type
User defined, customized data type Like structures in C Collection of various members Create the Data type and declare record variable which refers the user defined record type
50
25
26
OPEN, FETCH, CLOSE this is too muchisnt there a simpler way to do it ???
27
28
29
Cursor Variables
A cursor variable points to the current row in the result set of a multi-row query A cursor is static, a cursor variable is dynamic Declaring a cursor variable creates a pointer A cursor variable has data type REF CURSOR Cursor variables are used to pass query result sets between PL/SQL stored subprograms and various clients
30
Cursor Attributes
Example
Declare Cursor my_cur IS Select * from emp where deptno=10 FOR UPDATE; current_rec my_cur%rowtype; Begin . FETCH my_cur INTO current_rec; update emp set comm=1000 WHERE CURRENT OF my_cur;
62
31
Exceptions
Calling procedure Called procedure
PROCEDURE PROC1 ... IS ... BEGIN ... PROC2(arg1); ... EXCEPTION ... END PROC1;
PROCEDURE PROC2 ... IS ... BEGIN ... EXCEPTION ... END PROC2;
Control returns to calling procedure
10-63
Exception Block
Syntax . EXCEPTION WHEN name_of_exception1 THEN handler PL/SQL statements WHEN name_of_exception2 THEN handler END;
64
32
Exception
Any PL/SQL block can have its own exception block Exception block contains Name of the exception thrown HANDLER explains the actions to be performed when error occur Exception is not going to solve the current error condition.
65
66
33
Types of Exception
Exception
Pre-defined Exception
Userdefined
NonPredefined Exception
67
Pre-defined Exceptions
PL/SQL defined exceptions Sensed and mapped to the corresponding exception handler automatically User has to DEFINE it - handler No need to DECLARE and INVOKE
No_data_found Invalid_number Zero_divide Cursor_already_open Dup_val_on_index Too_many_rows
68
34
Example
DECLARE v_empno EMP.EMPNO%TYPE; BEGIN
INSERT INTO DEPT VALUES(55,Operations,NY); SELECT empno INTO v_empno FROM emp WHERE ename=ABC; DBMS_OUTPUT.PUT_LINE (v_empno); EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE (no employee found); END;
69
WHEN OTHERS
Unhandled exception can be trapped in the OTHERS category
Example .. EXCEPTION .. WHEN OTHERS THEN DBMS_OUTPUT,PUT_LINE (SQLCODE); DBMS_OUTPUT,PUT_LINE (SQLERRM); END;
When PL/SQL senses exception, handler is searched. If specific handler is not found OTHERS handler is executed Use SQLCODE & SQLERRM to print the error code and message
70
35
71
72
36
Example
DECLARE v_comm EMP.comm%TYPE; v_job EMP.job%TYPE; invalid_commisn EXCEPTION; BEGIN IF (v_job=MANAGER AND v_comm>500) THEN RAISE invalid_commisn; END IF; .. EXCEPTION WHEN invalid_commisn THEN . END;
73
74
37
Creating Procedures
10-75
1
xx xxx xxx xx xxx xxx ----- --- ------- --- --xx xxx xxx xx xxx xxx ----- --- ---
3 2
xx xxx xxx xx xxx xxx P P ----- --- ------- --- --P ----- --- ---
10-76
38
10-77
10-78
39
10-79
Easy maintenance
Improved performance
10-80
40
Anonymous Blocks
Unnamed PL/SQL blocks Compiled every time Not stored in the database Cannot be invoked by other applications Do not return values Cannot take parameters
Subprograms
Named PL/SQL blocks Compiled only once Stored in the database Named and, therefore, can be invoked by other applications Subprograms called functions must return values. Can take parameters
10-81
Procedures
10-82
41
YES
Use SHOW ERRORS command in SQL*Plus Create/edit procedure Compiler warnings/errors? View compiler warnings/errors
NO
Use USER/ALL/DBA_ ERRORS views
Execute procedure
10-83
Use the CREATE clause to create a stand-alone procedure that is stored in the Oracle database. Use the OR REPLACE option to overwrite an existing procedure. CREATE [OR REPLACE] PROCEDURE procedure_name [(parameter1 [mode] datatype1, parameter2 [mode] datatype2, ...)] IS|AS [local_variable_declarations; ...] BEGIN PL/SQL block -- actions; END [procedure_name];
10-84
42
Are declared after the subprogram name in the PL/SQL header Pass or communicate data between the calling environment and the subprogram Are used like local variables but are dependent on their parameterpassing mode:
An IN parameter mode (the default) provides values for a subprogram to process An OUT parameter mode returns a value to the caller An IN OUT parameter mode supplies an input value, which may be returned (output) as a modified value
10-85
-- Procedure definition, Formal_parameters CREATE PROCEDURE raise_sal(p_id NUMBER, p_sal NUMBER) IS BEGIN . . . END raise_sal; -- Procedure calling, Actual parameters (arguments) v_emp_id := 100; raise_sal(v_emp_id, 2000)
10-86
43
Parameter modes are specified in the formal parameter declaration, after the parameter name and before its data type. The IN mode is the default if no mode is specified.
IN (default)
Calling environment
OUT IN OUT
Procedure
10-87
IN
Default mode Value is passed into subprogram Formal parameter acts as a constant Actual parameter can be a literal, expression, constant, or initialized variable Can be assigned a default value
OUT
Must be specified Value is returned to the calling environment Uninitialized variable
IN OUT
Must be specified Value passed into subprogram; value returned to calling environment Initialized variable
Must be a variable
Must be a variable
10-88
44
10-89
10-90
45
CREATE OR REPLACE PROCEDURE format_phone (p_phone_no IN OUT VARCHAR2) IS BEGIN p_phone_no := '(' || SUBSTR(p_phone_no,1,3) || ') ' || SUBSTR(p_phone_no,4,3) || '-' || SUBSTR(p_phone_no,7); END format_phone; /
10-91
Use PL/SQL variables that are printed with calls to the DBMS_OUTPUT.PUT_LINE procedure. SET SERVEROUTPUT ON DECLARE v_emp_name employees.last_name%TYPE; v_emp_sal employees.salary%TYPE; BEGIN query_emp(171, v_emp_name, v_emp_sal); DBMS_OUTPUT.PUT_LINE('Name: ' || v_emp_name); DBMS_OUTPUT.PUT_LINE('Salary: ' || v_emp_sal); END;
10-92
46
1. 2. 3.
Use SQL*Plus host variables. Execute QUERY_EMP using host variables. Print the host variables.
VARIABLE b_name VARCHAR2(25) VARIABLE b_sal NUMBER EXECUTE query_emp(171, :b_name, :b_sal) PRINT b_name b_sal
10-93
10-94
47
10-95
-- Passing parameters using the named notation. EXECUTE add_dept (p_loc=>2400, p_name=>'EDUCATION')
10-96
48
10-97
Calling Procedures
You can call procedures using anonymous blocks, another procedure, or packages. You must own the procedure or have the EXECUTE privilege.
CREATE OR REPLACE PROCEDURE process_employees IS CURSOR cur_emp_cursor IS SELECT employee_id FROM employees; BEGIN FOR emp_rec IN cur_emp_cursor LOOP raise_salary(emp_rec.employee_id, 10); END LOOP; COMMIT; END process_employees; /
10-98
49
2 1 3
10-99
SELECT text FROM user_source WHERE name = 'ADD_DEPT' AND type = 'PROCEDURE' ORDER BY line;
10-100
50
Creating Functions
11-101
11-102
51
Creating Functions
The PL/SQL block must have at least one RETURN statement.
CREATE [OR REPLACE] FUNCTION function_name [(parameter1 [mode1] datatype1, . . .)] RETURN datatype IS|AS [local_variable_declarations; . . .] BEGIN PL/SQL Block -- actions; RETURN expression; END [function_name];
11-103
YES
Use SHOW ERRORS command in SQL*Plus Create/edit function Compiler warnings/errors? View compiler warnings/errors
NO
Use USER/ALL/DBA_ ERRORS views
Invoke function
11-104
52
Creating and Invoking a Stored Function Using the CREATE FUNCTION Statement: Example
CREATE OR REPLACE FUNCTION get_sal (p_id employees.employee_id%TYPE) RETURN NUMBER IS v_sal employees.salary%TYPE := 0; BEGIN SELECT salary INTO v_sal FROM employees WHERE employee_id = p_id; RETURN v_sal; END get_sal; / -- Invoke the function as an expression or as -- a parameter value. EXECUTE dbms_output.put_line(get_sal(100))
11-105
-- As a PL/SQL expression, get the results using a local -- variable SET SERVEROUTPUT ON DECLARE sal employees.salary%type; BEGIN sal := get_sal(100); DBMS_OUTPUT.PUT_LINE('The salary is: '|| sal); END; /
11-106
53
-- Use in a SQL statement (subject to restrictions) SELECT job_id, get_sal(employee_id) FROM employees;
...
11-107
11-108
54
11-109
11-110
55