Professional Documents
Culture Documents
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 Procedural statement executor
SQL
Benefits of PL/SQL
SQL
Application
SQL SQL
Other DBMSs
SQL
SQL IF...THEN
Application
SQL
ELSE SQL END IF; SQL
Better Performance
Processes multiple SQL statements simultaneously as a single block Reduces Network Traffic
Error Handling
Handles Errors/Exception effectively during execution of PL/SQL program Exception Caught can be used to take specific action
A Simple PL/SQL Block 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).
DECLARE
Variable Declaration
BEGIN
Program Execution
EXCEPTION
Exception Handling
END;
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
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; BEGIN SELECT column_name INTO variable_name FROM table_name [WHERE condition];
Composite or Collections
%ROWTYPE, RECORD, VARRAY , NESTED TABLE, TABLE
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
General Syntax for Declaring Constants
constant_name CONSTANT datatype := VALUE;
Value should be assigned when you declare it Assigning or Re-assigning the value in the exec section causes an error
Dynamically define the datatype of a column based on a database column Declare a record based on a user-defined type. 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 record_type_name;
record_name table_name%ROWTYPE;
record_name.column_name := value;
SELECT col1, col2 INTO record_name.col_name1, record_name.col_name2 FROM table_name [WHERE clause]; SELECT * INTO record_name FROM table_name [WHERE clause]; variable_name := record_name.col_name;
To assign a value to all fields in the record from a database table. 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; /
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
%NOTFOUND
FALSE DML/SELECT INTO SQL%NOTFOUND statement affects atleast one row TRUE No rows affected Returns the number of rows affected by the DML operations INSERT/UPDATE/DELETE SQL%ROWCOUNT
%ROWCOUNT
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;
Cursors Explicit Cursors - Attributes Use Cursor attributes to control data processing and avoiding errors in OPEN/FETCH/CLOSE statements
Attributes %FOUND Return Values TRUE - if fetch statement returns at least one row. FALSE, if fetch statement doesnt TRUE/FALSE No.of.rows returned TRUE/FALSE Example cursor_name%FOUND
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; Excersise : Print the output of all the employees in a given format using the while and for loop -> Cursor is implicit declared
Creating Procedures
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
CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters] IS Declaration section BEGIN Execution section EXCEPTION Exception section END
OUT
Must be Specified
IN OUT
Must be Specified
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
Named PL/SQL block that returns a value The Return General Syntax
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;
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
Removing Packages
DROP PACKAGE 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
Better Performance
Entire package is loaded into the memory when package is first referenced
Overloading
Multiple Sub-programs with the same name
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
General Syntax
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 ON table_name ====== Table Name [FOR EACH ROW] ==== Row Level or Statement Level WHEN (condition) ==== Row Level Trigger Condition BEGIN --sql statements END;
Triggers contd
Handling Multiple Situations using Conditional Predicates
Combine Several Triggering events into one by using special conditional predicates INSERTING,UPDATING,DELETING Usage IF [DELETING|INSERTING|UPDATING] THEN .. END IF;
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