You are on page 1of 40

Oracle 10g SQL/PL SQL

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

SQL statement executor Oracle server

Benefits of PL/SQL

SQL

Application

SQL SQL

Other DBMSs

SQL

SQL IF...THEN

Application

SQL
ELSE SQL END IF; SQL

Oracle with PL/SQL

Advantages of PL/SQL Block Structures


Blocks of code which can be nested inside each other

Procedural Language Capability


Use of Conditional Statements (if-else) / loops like (FOR/WHILE)

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 DECLARE Section


Starts with the optional reserved keyword DECLARE Used to declare any placeholders Placeholders can be
Variables User Defined Exceptions Cursors Constants

Each Declaration/Assignment ends with a semi-colon


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

Each statement ends with a semi-colon


E.g BEGIN SELECT COL1 INTO v_variable FROM TABLE; END;

PL/SQL Block Exception Section


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;

Block Types in PL/SQL

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];

PL/SQL Placeholders Variables contd


Types of Variables
PL/SQL Variables Scalar Holds a Single Value
CHAR,VARCHAR2,LONG,NUMBER,BINARY_INTEGER,BOOLEAN DATE,TIMESTAMP, %TYPE Attribute - Syntax : identifier Table1.column%TYPE;

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

PL/SQL Placeholders - Records


Records are composite data types ( Combination of Scalar Data types) Can be visualized as a row of data First Define a Composite Datatype and then declare a record for that type General Syntax TYPE record_type_name IS RECORD (first_col_name column_datatype, second_col_name column_datatype, ...); 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

PL/SQL Placeholders Records contd


Syntax of Records TYPE record_type_name IS RECORD (column_name1 datatype, column_name2 datatype, ...); col_name table_name.column_name%type; Usage Define a composite datatype, where each field is scalar.

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;

PL/SQL Placeholders Records contd..


Passing Values To and From a Record
Syntax record_name.col_name := value; Usage To directly assign a value to a specific column of a record. To directly assign a value to a specific column of a record, if the record is declared using %ROWTYPE. To assign values to each field of a record from the database table.

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; /

Writing Executable Statements


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
v_date := TO_DATE ('January 13, 2001','Month DD, YYYY');

Interacting with Oracle Server


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 Sample Exercise Playaround with Employee Table using PL/SQL sub-programs

Conditional Statements in PL/SQL


PL/SQL supports conditional and iterative statements like other programming languages IF-THEN-ELSIF- ELSE Statement IF condition 1 THEN 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;] END;

Iterative Control - Loop Statements


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 statements; END 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 Implicit Cursor Attribues


Attributes %FOUND Return Value TRUE DML/SELECT INTO statement affects atleast one row FALSE No rows affected Example SQL%FOUND

%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;

How to use Explicit Cursors ?


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 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

%NOTFOUND %ROWCOUNT %ISOPEN

cursor_name%NOTFO UND cursor_name%ROWCO UNT 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; Excersise : Print the output of all the employees in a given format using the while and for loop -> Cursor is implicit declared

Advanced Explicit Cursor Concepts


Cursors with parameters Parameters in cursors makes it more reusable instead of hardcoding CURSOR cursor_name [(parameter_name datatype, ...)] IS select_statement; 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

Handling Exceptions in PL/SQL


PL/SQL provides feature to handle exceptions in a separate block General Structure of Exception EXCEPTION -> Exception Block 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

Handling Exceptions Exception Types


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
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

Execute a Stored Procedure using


Exec procedure_name inside a BEGIN END; Inside another procedure - procedure_name;

Creating Procedures with parameters


IN
Default Mode Value is passed to the sub-program Can be assigned a default value Actual Parameter can be a variable or a constant

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

Packages Overview contd


General Syntax for Package Specification
CREATE OR REPLACE PACKAGE package_name IS public type and item declarations sub-programs specifications END package_name;

Package Body Syntax


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 ];

Invoking Package procedures


EXECUTE package_name.procedure_name(paramter values); EXECUTE schema_name.package_name.procedure_name(parameter vaues);

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;

Old and New Qualifiers Applicable only for ROW Triggers


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

You might also like