Oracle 10g SQL-pl SQL

download Oracle 10g SQL-pl SQL

of 40

Transcript of Oracle 10g SQL-pl SQL

  • 8/2/2019 Oracle 10g SQL-pl SQL

    1/40

  • 8/2/2019 Oracle 10g SQL-pl SQL

    2/40

    Oracle 10g SQL/PL SQL

  • 8/2/2019 Oracle 10g SQL-pl SQL

    3/40

    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

  • 8/2/2019 Oracle 10g SQL-pl SQL

    4/40

    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.

  • 8/2/2019 Oracle 10g SQL-pl SQL

    5/40

  • 8/2/2019 Oracle 10g SQL-pl SQL

    6/40

    Application

    OtherDBMSs

    Application

    Oracle with

    PL/SQL

    SQL

    SQL

    SQL

    SQL

    SQL

    IF...THEN

    SQL

    ELSE

    SQL

    END IF;

    SQL

    Benefits of PL/SQL

  • 8/2/2019 Oracle 10g SQL-pl SQL

    7/40

    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

  • 8/2/2019 Oracle 10g SQL-pl SQL

    8/40

    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

    BEGIN

    END;

    Exception Handling

    EXCEPTION

    Variable Declaration

    Program Execution

  • 8/2/2019 Oracle 10g SQL-pl SQL

    9/40

    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 DECLAREv_variable VARCHAR2(5);

  • 8/2/2019 Oracle 10g SQL-pl SQL

    10/40

  • 8/2/2019 Oracle 10g SQL-pl SQL

    11/40

    PL/SQL Block Exception Section

    Optional Section; starts with a reserved keywordexception

    Used for handling errors in the program section forthe PL/SQL block to terminate gracefully

    Any unhandled exceptions ends the program abruptly Each statement ends with a semicolon

    E.g EXCEPTIONWHEN exception1 [ or exception2 ..] THEN

    statement1;

    statement2;

    WHEN exception3 THEN

    statement3;

    WHEN OTHERS THEN

    statement4;

  • 8/2/2019 Oracle 10g SQL-pl SQL

    12/40

    Block Types in PL/SQL

    [DECLARE]

    BEGIN--statements

    [EXCEPTION]

    END;

    PROCEDURE name

    IS

    BEGIN--statements

    [EXCEPTION]

    END;

    FUNCTION name

    RETURN datatype

    ISBEGIN

    --statements

    RETURN value;

    [EXCEPTION]

    END;

    ANONYMOUS PROCEDURE FUNCTION

  • 8/2/2019 Oracle 10g SQL-pl SQL

    13/40

    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 FROMtable_name [WHERE condition];

  • 8/2/2019 Oracle 10g SQL-pl SQL

    14/40

    PL/SQL Placeholders Variables contd

    Types of Variables PL/SQL Variables

    Scalar Holds a Single Value CHAR,VARCHAR2,LONG,NUMBER,BINARY_INTEGER,BOOLEA

    N 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

  • 8/2/2019 Oracle 10g SQL-pl SQL

    15/40

    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 execsection causes an error

  • 8/2/2019 Oracle 10g SQL-pl SQL

    16/40

    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

  • 8/2/2019 Oracle 10g SQL-pl SQL

    17/40

    PL/SQL Placeholders Records contdSyntax of Records Usage

    TYPE record_type_name IS RECORD(column_name1 datatype, column_name2

    datatype, ...);

    Define a composite datatype, where each field isscalar.

    col_name table_name.column_name%type; Dynamically define the datatype of a columnbased on a database column

    record_name record_type_name; Declare a record based on a user-defined type.

    record_name table_name%ROWTYPE; Dynamically declare a record based on an entirerow of a table. Each column in the tablecorresponds to a field in the record.

  • 8/2/2019 Oracle 10g SQL-pl SQL

    18/40

    PL/SQL Placeholders Records contd..

    Passing Values To and From a Record

    Syntax Usage

    record_name.col_name := value; To directly assign a value to a specificcolumn of a record.

    record_name.column_name := value; To directly assign a value to a specificcolumn of a record, if the record isdeclared using %ROWTYPE.

    SELECT col1, col2 INTOrecord_name.col_name1,record_name.col_name2 FROMtable_name [WHERE clause];

    To assign values to each field of arecord from the database table.

    SELECT * INTO record_name FROMtable_name [WHERE clause];

    To assign a value to all fields in therecord from a database table.

    variable_name :=record_name.col_name;

    To get a value from a record columnand assigning it to a variable

  • 8/2/2019 Oracle 10g SQL-pl SQL

    19/40

    DBMS_OUTPUT.PUT_LINE

    Oracle Supplied packaged procedure

    An alternative for displaying data from PL/SQL Block Must be enabled in SQLPLUS session using thecommand

    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;

    /

  • 8/2/2019 Oracle 10g SQL-pl SQL

    20/40

    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');

  • 8/2/2019 Oracle 10g SQL-pl SQL

    21/40

    Interacting with Oracle Server SELECT Statements in PL/SQL

    SELECT select_list INTO [ variable_names ] FROM table1WHERE [ 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/SQLsub-programs

  • 8/2/2019 Oracle 10g SQL-pl SQL

    22/40

    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;

    ELSEstatement 4;

    END IF;

    CASE ExpressionCASE selector

    WHEN expression1 THEN result1

    WHEN expression2 THEN result2

    ...

    WHEN expressionN THEN resultN

    [ELSE resultN+1;]

  • 8/2/2019 Oracle 10g SQL-pl SQL

    23/40

    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 leastonce 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 timesFOR counter IN [REVERSE] lower_bound..upper_bound LOOP

    statements

    END LOOP;

    WHILE Loop

    To be used as long as a condition is trueWHILE condition LOOP

    statements;

    END LOOP;

  • 8/2/2019 Oracle 10g SQL-pl SQL

    24/40

    Cursors Implicit and Explicit

    Temporary work area created in system memorywhen SQL statements are executed

    Work area is used to store the data retrieved from thedatabase ( 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

  • 8/2/2019 Oracle 10g SQL-pl SQL

    25/40

    Cursors Implicit Cursor Attribues

    Attributes Return Value Example

    %FOUND TRUE DML/SELECT INTOstatement affects atleast onerow

    FALSE No rows affected

    SQL%FOUND

    %NOTFOUND FALSE DML/SELECT INTOstatement affects atleast one

    rowTRUE No rows affected

    SQL%NOTFOUND

    %ROWCOUNT Returns the number of rowsaffected by the DMLoperationsINSERT/UPDATE/DELETE

    SQL%ROWCOUNT

  • 8/2/2019 Oracle 10g SQL-pl SQL

    26/40

    Cursors Explicit Cursors

    Is a SELECT statement that is explicitly defined in thedeclaration 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;

  • 8/2/2019 Oracle 10g SQL-pl SQL

    27/40

    Cursors Explicit Cursors - Attributes

    Use Cursor attributes to control data processing andavoiding errors in OPEN/FETCH/CLOSE statements

    Attributes Return Values Example

    %FOUND TRUE - if fetch statementreturns at least one row.

    FALSE, if fetch statementdoesnt

    cursor_name%FOUND

    %NOTFOUND TRUE/FALSE cursor_name%NOTFOUND

    %ROWCOUNT No.of.rows returned cursor_name%ROWCOUNT

    %ISOPEN TRUE/FALSE cursor_name%ISOPEN

  • 8/2/2019 Oracle 10g SQL-pl SQL

    28/40

    Cursors Explicit Cursors Using Loops

    While Loop can be used to get the values from thecursor 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 -> Cursor is implicit declaredstatements;

    END LOOP;

    Excersise : Print the output of all the employees in a given format using the while and for loop

  • 8/2/2019 Oracle 10g SQL-pl SQL

    29/40

    Advanced Explicit Cursor Concepts Cursors with parameters

    Parameters in cursors makes it more reusable instead of hardcodingCURSOR cursor_name [(parameter_name datatype, ...)]

    IS select_statement;

    Pass the argument when the cursor is to be openedOpen 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 exclusivelock

    FOR UPDATE clause with or without a column name has to bespecified in the declaration

    WHERE CURRENT OF clause explicitly mentions to update thecurrent 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

  • 8/2/2019 Oracle 10g SQL-pl SQL

    30/40

    Handling Exceptions in PL/SQL

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

  • 8/2/2019 Oracle 10g SQL-pl SQL

    31/40

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

    Can be avoided using WHEN OTHERS or using PRAGMAEXCEPTION_INIT

    PRAGMA EXCEPTION_INIT (exception_var_name,); User-Defined Exceptions

    Exceptions based on business rules

    Declared in the Declare Section, Explicitly raised in the executionsection,Referenced in the exception section

    RAISE_APPLICATION_ERROR

    Built in procedure to display the user defined error messageswhose range is between -20000 and -20999

    RAISE_APPLICATION_ERROR (error_number,error_message);

  • 8/2/2019 Oracle 10g SQL-pl SQL

    32/40

    Creating Procedures Named PL/SQL Block to perform any task Contains a Header and a Body

    Header consists of name of procedure and parameters orvariables passed to the procedure

    Body consists of DECLARATION,BEGIN and EXECUTIONsection

    General SyntaxCREATE [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

  • 8/2/2019 Oracle 10g SQL-pl SQL

    33/40

    Creating Procedures with parameters

    IN OUT IN OUT

    Default Mode Must be Specified Must be Specified

    Value is passed to thesub-program

    Returned to the callingenvironment

    Passed into thesubprogram andreturned

    Can be assigned adefault value

    Cannot be assigned adefault value

    Cannot be assigned adefault value

    Actual Parameter canbe a variable or aconstant

    Has to be a variable Has to be a variable

  • 8/2/2019 Oracle 10g SQL-pl SQL

    34/40

    Creating Functions Named PL/SQL block that returns a value The Return General SyntaxCREATE [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);

  • 8/2/2019 Oracle 10g SQL-pl SQL

    35/40

    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 thespecification

    Private procedures/functions which are not defined in the packagespecification

    Public Constructs can be referenced across the Oracle serverenvironment

    Private Constructs can be referenced only by other constructs of thesame package

    Package Specification can exist without a body but not vice-versa

  • 8/2/2019 Oracle 10g SQL-pl SQL

    36/40

    Packages Overview contd General Syntax for Package Specification

    CREATE OR REPLACE PACKAGE package_nameIS

    public type and item declarations

    sub-programs specifications

    END package_name;

    Package Body SyntaxCREATE 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);

  • 8/2/2019 Oracle 10g SQL-pl SQL

    37/40

    Advantages of Packages

    Modularity : Encapsulate logically relatedprogramming structures

    Easier Application Design : Having a Specificationand 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

  • 8/2/2019 Oracle 10g SQL-pl SQL

    38/40

    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 SyntaxCREATE [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;

  • 8/2/2019 Oracle 10g SQL-pl SQL

    39/40

    Triggers contd Handling Multiple Situations using Conditional Predicates

    Combine Several Triggering events into one by using special conditional predicatesINSERTING,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. and :NEW.

    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

  • 8/2/2019 Oracle 10g SQL-pl SQL

    40/40

    Thank You