Agenda
PL/SQL - Introduction - Benefits and Advantages PL/SQL Block - Declare, Begin and Exception Section Block Types PL/SQL Placeholders - Variables,Constants,Records DBMS_OUTPUT.PUT_LINE Writing Executable Statements Interacting with Oracle Server Conditional Statements in PL/SQL Iterative Control Cursors Handling Exceptions Procedures and Functions Packages Triggers
What is PL/SQL?
PL/SQL stands for Procedural Language extension of SQL PL/SQL is a combination of SQL along with the procedural features of programming languages. It was developed by Oracle Corporation in the early 90s to enhance the capabilities of SQL.
PL/SQL Environment
PL/SQL engine PL/SQL block PL/SQL block PL/SQL SQL Procedural statement executor
Benefits of PL/SQL
SQL SQL SQL SQL
Applicatio n
Other DBMSs
SQL
Applicatio n
Blocks of code which can be nested inside each other Use of Conditional Statements (if-else) / loops like (FOR/WHILE) Processes multiple SQL statements simultaneously as a single block Reduces Network Traffic Handles Errors/Exception effectively during execution of PL/SQL program Exception Caught can be used to take specific action
Better Performance
Error Handling
Each PL/SQL program consists of SQL and PL/SQL statements which from a PL/SQL block A PL/SQL Block consists of three sections:
The Declaration section (optional). The Execution section (mandatory). The Exception (or Error) Handling section (optional).
DECLAR E BEGI N
Variable Declaration
Program Execution
EXCEPTIO N END ;
Exception Handling
Starts with the optional reserved keyword DECLARE Used to declare any placeholders Placeholders can be
Variables User Defined Exceptions Cursors Constants E.g DECLARE v_variable VARCHAR2(5);
PL/SQL Block Execution Section Starts with a Mandatory Reserved Keyword BEGIN and ends with END Section consists of the program logic to perform any task Programmatic constructs includes
Loops Conditional Statements SQL Statements E.g BEGIN SELECT COL1 INTO v_variable FROM TABLE; END;
Optional Section; starts with a reserved keyword exception Used for handling errors in the program section for the PL/SQL block to terminate gracefully Any unhandled exceptions ends the program abruptly Each statement ends with a semicolon
E.g EXCEPTION
WHEN exception1 [ or exception2 ..] THEN statement1; statement2; WHEN exception3 THEN statement3; WHEN OTHERS THEN statement4;
ANONYMOUS
[DECLARE] BEGIN --statements [EXCEPTION] END;
PROCEDURE
PROCEDURE name IS BEGIN --statements [EXCEPTION] END;
FUNCTION
FUNCTION name RETURN datatype IS BEGIN --statements RETURN value; [EXCEPTION] END;
PL/SQL Placeholders Variables Placeholders are temporary storage of data which can be any Variables, Constants and Records PL/SQL Variables
Declare and Initialise variables in the DECLARE Section Assign new values to variables in the Executable Section Syntax : variable_name datatype [NOT NULL := value ]; Methods DECLARE n_salary number (6); v_dept varchar2(10) NOT NULL := HR Dept;
Types of Variables
CHAR,VARCHAR2,LONG,NUMBER,BINARY_INTEGER,BOOLEA N DATE,TIMESTAMP, %TYPE Attribute - Syntax : identifier Table1.column%TYPE; %ROWTYPE, RECORD, VARRAY , NESTED TABLE, TABLE
Composite or Collections
LOB ( Large Objects ) BLOB,CLOB Non PL/SQL Variables Bind and Host Variables Avoid HardParsing when called from external applications
PL/SQL Placeholders Constants Value used in the PL/SQL block that remains unchanged in the whole program
Value should be assigned when you declare it Assigning or Re-assigning the value in the exec section causes an error
col_name table_name.column_name%type; record_name table_name%ROWTYPE; Advantages No need to explicitly declare variables for all the columns of the table Altering the column specification does not require modifying the code Disadvantages ROWTYPE declaration fields will create for all columns of the table Creating a RECORD only creates a data type. Values are required to be assigned to record to use them
Dynamically define the datatype of a column based on a database column Declare a record based on a user-defined type.
record_name record_type_name;
record_name table_name%ROWTYPE;
Dynamically declare a record based on an entire row of a table. Each column in the table corresponds to a field in the record.
record_name.column_name := value; To directly assign a value to a specific column of a record, if the record is declared using %ROWTYPE. SELECT col1, col2 INTO record_name.col_name1, record_name.col_name2 FROM table_name [WHERE clause]; To assign values to each field of a record from the database table.
SELECT * INTO record_name FROM To assign a value to all fields in the table_name [WHERE clause]; record from a database table. variable_name := record_name.col_name; To get a value from a record column and assigning it to a variable
DBMS_OUTPUT.PUT_LINE
Oracle Supplied packaged procedure An alternative for displaying data from PL/SQL Block Must be enabled in SQLPLUS session using the command
SET SERVEROUTPUT ON
DECLARE v_sal NUMBER(9,2) := 10000; BEGIN v_sal := v_sal/12; DBMS_OUTPUT.PUT_LINE ('The monthly salary is ' || TO_CHAR(v_sal)); END; /
Guidelines for Identifiers Variables can contain upto 30 chars and begin with a alphabetic character Can contain numbers,dollarsigns,underscore Cannot contain hyphens,slashes and spaces Should not be a reserved word Character and Date literals must be enclosed in single quotes Single-line comments with two dashes ( --) Multi-line comments with /* .. */ Programming Guidelines Documenting Code with comments Following naming conventions for the code Enhancing Readability by indenting SQL Functions can be used in procedural statements except DECODE Group Functions E.g v_ename := LOWER(v_ename); Datatype Conversion functions to be used before assigning
SELECT Statements in PL/SQL SELECT select_list INTO [ variable_names ] FROM table1 WHERE [ Filter Criteria ] Queries must return only a single row to avoid exceptions Manipulating Data to database using DML Commands in PL/SQL Insert Statements in PL/SQL Update Statements in PL/SQL Delete Statements in PL/SQL Transaction Control Statements in PL/SQL Use of COMMIT/ROLLBACK to terminate a transaction explicitly
statement 1; statement 2; ELSIF condtion2 THEN statement 3; ELSE statement 4; END IF; CASE Expression CASE selector
WHEN expression1 THEN result1 WHEN expression2 THEN result2 ... WHEN expressionN THEN resultN [ELSE resultN+1;]
Loops repeat a statement or sequence of statements multiple times. Basic Loop Types Basic Loop Simple Loop when a set of statements has to be executed at least once and should contain a EXIT condition to avoid infinite loop LOOP statements; EXIT [WHEN condition]; END LOOP; FOR Loop Execute a condition for a pre-determined number of times FOR counter IN [REVERSE] lower_bound..upper_bound LOOP
statements END LOOP; WHILE Loop To be used as long as a condition is true WHILE condition LOOP
Cursors Implicit and Explicit Temporary work area created in system memory when SQL statements are executed Work area is used to store the data retrieved from the database ( Active Set ) Types of Cursor
Implicit Created automatically when DML and SELECT statements OPEN/FETCH/CLOSE of Cursor is done automatically Explicit Created by user when executing SELECT statements OPEN/FETCH/CLOSE should be done manually
Cursors Explicit Cursors Is a SELECT statement that is explicitly defined in the declaration section with a name General Syntax
CURSOR cursor_name IS select_statement; DECLARE the cursor in the declaration section OPEN the cursor in the Execution Section Command : OPEN cursor_name; FETCH the data from cursor into PL/SQL variables or records in the Execution Section inside a loop FETCH cursor_name INTO record_name CLOSE the cursor in the Execution Section before you end the PL/SQL Block. CLOSE cursor_name;
Cursors Explicit Cursors - Attributes Use Cursor attributes to control data processing and avoiding errors in OPEN/FETCH/CLOSE statements
Attributes %FOUND Return Values Example TRUE - if fetch statement cursor_name%FOUND returns at least one row. FALSE, if fetch statement doesnt %NOTFOUND %ROWCOUNT %ISOPEN TRUE/FALSE No.of.rows returned TRUE/FALSE cursor_name %NOTFOUND cursor_name %ROWCOUNT cursor_name%ISOPEN
Cursors Explicit Cursors Using Loops While Loop can be used to get the values from the cursor into a PL/SQL record variable Most commonly used is the FOR loop
Shortcut to process the explicit cursors Implicit Open , Fetch, Exit and Close occurs PL/SQL Record variable is implicitly declared
FOR record_name IN cursor_name LOOP -> Cursor is explicitly declared and used statements; END LOOP; FOR record_name IN ( SELECT .QUERY ) LOOP statements; END LOOP; -> Cursor is implicit declared
Excersise : Print the output of all the employees in a given format using the while and for loop
Cursors with parameters Parameters in cursors makes it more reusable instead of hardcoding CURSOR cursor_name [(parameter_name datatype, ...)] select_statement;
IS
Pass the argument when the cursor is to be opened Open cursor_name (:variable_name or constant value) Default Values can be used in the parameters when cursor is declared SELECT FOR UPDATE in Cursors Used to update values present in the table by obtaining a exclusive lock FOR UPDATE clause with or without a column name has to be specified in the declaration WHERE CURRENT OF clause explicitly mentions to update the current row fetched Important advantage of using WHERE CURRENT OF is to avoid using multiple update statements and conditional looping Exercise : Update the joining date of the employee table for all the records using WHERE CURRENT OF
WHEN ex_name1 THEN -Error handling statements WHEN ex_name2 THEN -Error handling statements WHEN Others THEN -Error handling statements END;
When Exceptions are raised, oracle searches for an appropriate exception handler in the exception section If none of them are present, then oracle abruptly ends the execution with an error WHEN OTHERS should always be the last clause in the exception handling section
Exception Types Named System Exceptions Automatically raised when there is a Oracle error Known Exception E.g NO_DATA_FOUND;ZERO_DIVIDE;TOO_MANY_ROWS etc Unnamed System Exceptions Unknown Exception that are less frequent and oracle does not give a meaningful explanation Can be avoided using WHEN OTHERS or using PRAGMA EXCEPTION_INIT PRAGMA EXCEPTION_INIT (exception_var_name, <oracle_error_no>); User-Defined Exceptions Exceptions based on business rules Declared in the Declare Section, Explicitly raised in the execution section,Referenced in the exception section RAISE_APPLICATION_ERROR Built in procedure to display the user defined error messages whose range is between -20000 and -20999 RAISE_APPLICATION_ERROR (error_number, error_message);
Creating Procedures
CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters] IS Declaration section BEGIN Execution section EXCEPTION Exception section END
Named PL/SQL Block to perform any task Contains a Header and a Body Header consists of name of procedure and parameters or variables passed to the procedure Body consists of DECLARATION,BEGIN and EXECUTION section General Syntax
Returned to the calling Passed into the environment subprogram and returned Cannot be assigned a default value Has to be a variable Cannot be assigned a default value Has to be a variable
Creating Functions
CREATE [OR REPLACE] FUNCTION function_name [parameters] RETURN return_datatype; IS Declaration_section BEGIN - Execution_section Return return_variable; EXCEPTION exception section Return return_variable; END;
Named PL/SQL block that returns a value The Return General Syntax
Executing a Function
variable_name := function_name(parameters); SELECT function_name(parameters); FROM dual; Select STATEMENTS like any other Oracle defined functions dbms_output.put_line(function_name);
Packages - Overview
Collection of PL/SQL objects that are grouped together Package can contain Procedure,Functions,Cursors,Variables,Constants Contains a Package Specification and a Body Package Specification Contains the definition or specification of all elements in a package Contains Public Variables required for accessing across the elements of the package Package Body Definition of all the elements of the package defined in the specification Private procedures/functions which are not defined in the package specification Public Constructs can be referenced across the Oracle server environment Private Constructs can be referenced only by other constructs of the same package Package Specification can exist without a body but not vice-versa
IS
CREATE OR REPLACE PACKAGE package_name public type and item declarations sub-programs specifications
END package_name;
CREATE OR REPLACE PACKAGE BODY package_name IS [ declarations of variables and types ] [ specification and SELECT statement of cursors ] [ specification and body of modules ] [ BEGIN executable statements ] [ EXCEPTION exception handlers ] END [ package_name ];
Advantages of Packages
Modularity : Encapsulate logically related programming structures Easier Application Design : Having a Specification and Body Hiding Information
Public and Private Constructs Entire package is loaded into the memory when package is first referenced Multiple Sub-programs with the same name
Better Performance
Overloading
Triggers
PL/SQL block structure is fired implicitly when a DML statement is executed on a database table/view Types of Trigger
Row level - Triggered for each row updated , inserted or deleted Statement level Triggered for each sql statement executed Before and After Triggers Perform action before or after triggering action
CREATE [OR REPLACE ] TRIGGER trigger_name {BEFORE | AFTER | INSTEAD OF } ======= Events {INSERT [OR] | UPDATE [OR] | DELETE} === DML Action [OF col_name] ======= Column name or List Table Name
General Syntax
ON table_name ======
[FOR EACH ROW] ==== Row Level or Statement Level WHEN (condition) ==== Row Level Trigger Condition BEGIN --sql statements END;
Triggers contd
END IF;
OLD and :NEW to access the before and after value of the column value that is modified :OLD.<col_name> and :NEW.<col_name>
Guidelines for Designing Triggers Perform related action based on specific operation Do not design triggers to duplicate functionality of Oracle E.g Integrity Checks Avoid Excessive use of triggers which can be difficult to maintain Firing Sequence of Triggers BEFORE Statement Trigger BEFORE Row Trigger AFTER Row Trigger AFTER Statement Trigger
Thank You