Pls Ql 4 Sub Programs

Embed Size (px)

Citation preview

  • 8/22/2019 Pls Ql 4 Sub Programs

    1/32

    Procedures and Functions

  • 8/22/2019 Pls Ql 4 Sub Programs

    2/32

    CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 2

    Objectives

    At the end of this session, you will be able to:

    Understand subprograms and their need

    Comprehend the difference between stored and unstoredsubprograms

    Create and drop stored procedures and functions

    Apply different parameter modes in subprograms

    Understand and use procedures and functions that are local to

    a stored subprogram Understand the different data dictionary views

  • 8/22/2019 Pls Ql 4 Sub Programs

    3/32

    CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 3

    Agenda

    Need for subprograms

    Creating Stored Procedures

    RAISE_APPLICATION_ERROR

    Parameter Modes IN, OUT and IN OUT

    Invoking stored procedures from SQL*Plus and PL/SQL Block

    Examples of stored procedures and their invocation

    Creating Stored Functions

    Calling Stored Functions from different locations in DML and

    SELECT Queries Local Procedures and Functions within a stored subprogram

    Parameter passing mechanisms

    Privileges related to functions and procedures

    Dropping procedures and functions

    Data dictionary views related to subprograms USER_OBJECTS

    USER_SOURCE

    USER_PROCEDURES

    USER_ERRORS

  • 8/22/2019 Pls Ql 4 Sub Programs

    4/32

    CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 4

    Subprograms in PL/SQL

    PL/SQL blocks are anonymous, can not be called from otherPL/SQL blocks

    Subprogram is a named PL/SQL block that could be either Stored Procedure, or

    Stored Function, or

    Package

    Procedures and Functions behave similar to procedures of

    other 3GLs

  • 8/22/2019 Pls Ql 4 Sub Programs

    5/32

    CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 5

    Syntax for Creating a Procedure

    Stored Procedure

    A stored procedure is a named PL/SQL block that performs anaction. It is stored in the database as a database object forrepeated execution.

    CREATE [ OR REPLACE ] PROCEDUREproc_name[(argument [mode] data type,argument [mode] data type,)]

    -- PROCEDURES and FUNCTIONS may or may not acceptarguments

    IS

    Local PL/SQL variable declarations

    BEGIN

    Define action performed by the procedure

    EXCEPTION

    Handle exceptions, if any

    END [ proc_name];

    /

  • 8/22/2019 Pls Ql 4 Sub Programs

    6/32

    CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 6

    RAISE_APPLICATION_ERROR Procedure

    This procedure is used to display error messages along witherror numbers

    ExampleRAISE_APPLICATION_ERROR(-20001, Invalid

    Employee);

    Note:

    When called, RAISE_APPLICATION_ERROR ends a subprogram, rollsback any database changes it made, and returns a user-defined errormessage to the application

    Error numbers should be between -20000 and -20999

  • 8/22/2019 Pls Ql 4 Sub Programs

    7/32CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 7

    Parameters Modes in Procedures and Functions

    Formal parameters can have three modes IN, OUT or IN OUT whichdecides the behavior of parameters

    IN OUT IN OUT

    Default parameter mode Must be specified Must be specified

    Value is passed intosubprograms

    Value is returned tothe callingenvironment

    Value is passed intosubprogram andformatted/changedvalue is returned to thecalling environment

    Formal parameter acts as

    a constant inside asubprogram

    Formal parameter

    acts as a uninitializedvariable, as thesubprogram willassign value to it

    Formal parameter acts

    as a initialized variable,as the callingenvironment will pass avalue for it.

    Actual parameter can bean expression, constantor initialized variable

    Actual parametermust be a variable

    Actual parameter mustbe a variable

  • 8/22/2019 Pls Ql 4 Sub Programs

    8/32CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 8

    IN Parameter: Example

    CREATE OR REPLACE PROCEDURE

    raise_salary (p_eno emp.empno%TYPE)

    IS

    vsal emp.sal%type;BEGIN

    SELECT sal into vsal FROM emp WHERE empno=p_eno;

    IF vsal

  • 8/22/2019 Pls Ql 4 Sub Programs

    9/32CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 9

    Invoking a Procedure

    There are two methods to Invoke a Procedure

    Invoke a Procedure from another PL/SQL block

    e.g.

    BEGIN

    raise_salary(1002);

    END;

    /

    Invoke a procedure from SQL*Plus environment by using

    EXECUTE commande.g.

    -- PROCEDURE call with parameter

    EXECUTE raise_salary(1002);

    Note: If no parameters are specified for a procedure, directly specify

    procedure name without any parenthesis

    e. g. EXECUTE procedure_name;

  • 8/22/2019 Pls Ql 4 Sub Programs

    10/32CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 10

    OUT Parameter: Example

    CREATE OR REPLACE PROCEDURE query_emp

    ( p_eno IN emp.empno%TYPE,

    p_name OUT emp.ename%TYPE,

    p_sal OUT emp.sal%TYPE)

    IS

    BEGIN

    SELECT ename , sal INTO p_name , p_sal FROM emp

    WHERE empno = p_eno;

    EXCEPTIONWHEN NO_DATA_FOUND THEN

    RAISE_APPLICATION_ERROR(-20001, Employee does notexist);

    END query_emp;

    /

  • 8/22/2019 Pls Ql 4 Sub Programs

    11/32

    CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 11

    Invoking a Procedure Having OUT Parameters

    SQL> VARIABLE name VARCHAR2(20)

    SQL> VARIABLE salary NUMBER

    SQL> EXECUTE query_emp(1001,:name,:salary)

    SQL> PRINT name salary

    Note: The use of colon (:) is to reference the host variable inthe EXECUTE syntax

  • 8/22/2019 Pls Ql 4 Sub Programs

    12/32

    CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 12

    IN OUT Parameter: Example

    CREATE OR REPLACE PROCEDURE emp_salary_increase1

    (p_salary IN OUT emp.sal%TYPE)

    ISBEGIN

    IF p_salary between 1000 and 2000 THEN

    p_salary := p_salary * 1.2;

    ELSIF p_salary between 2001 and 3000 THEN

    p_salary := p_salary * 1.3;ELSIF p_salary > 3000 THEN

    p_salary := p_salary* 1.4;

    END IF;

    EXCEPTION

    WHEN OTHERS THENDBMS_OUTPUT.PUT_LINE(SQLERRM);

    END;

    /

  • 8/22/2019 Pls Ql 4 Sub Programs

    13/32

    CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 13

    IN OUT Parameter (Contd.)

    This PL/SQL block shows how to execute the above'emp_salary_increase' procedure

    DECLARE

    CURSOR updated_sal IS SELECT empno, sal FROM emp;

    pre_sal emp.sal%TYPE;

    BEGIN

    FOR emp_rec IN updated_sal LOOPpre_sal := emp_rec.sal;

    emp_salary_increase1 (emp_rec.sal);

    DBMS_OUTPUT.PUT_LINE(' The salary of ' ||

    emp_rec.empno ||' will be increased from '|| pre_sal

    || ' to '|| (emp_rec.sal));END LOOP;

    END;

    /

  • 8/22/2019 Pls Ql 4 Sub Programs

    14/32

    CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 14

    Syntax for Creating a Function

    A function is a named PL/SQL block that performs a task andreturns a value to the calling environment.

    Syntax:

    CREATE [ OR REPLACE ] FUNCTION function_name

    [( argument [mode] data type, argument [mode] datatype )]

    RETURN data type

    ISLocal PL/SQL variable declarations

    BEGIN

    Define task performed by the function and return

    result using RETURN statement

    EXCEPTION

    Handle exceptions if anyEND [ function_name];

  • 8/22/2019 Pls Ql 4 Sub Programs

    15/32

    CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 15

    Functions in PL/SQL

    Example 1

    CREATE OR REPLACE FUNCTION cal_bonus

    ( p_eno emp.empno%TYPE )RETURN NUMBER

    IS

    v_sal emp.sal%TYPE;

    BEGIN

    SELECT sal INTO v_sal FROM emp

    WHERE empno = p_eno;RETURN (v_sal * 0.1);

    EXCEPTION

    WHEN NO_DATA_FOUND THEN

    RETURN -1;

    END;

  • 8/22/2019 Pls Ql 4 Sub Programs

    16/32

    CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 16

    Functions in PL/SQL

    Example 2

    CREATE OR REPLACE FUNCTION chk_dept

    (p_deptno dept.deptno%TYPE) RETURNBOOLEAN

    IS

    v_deptno dept.deptno%type;

    BEGIN

    SELECT deptno into v_deptno FROM deptWHERE deptno = p_deptno;

    RETURN TRUE;

    EXCEPTION

    WHEN NO_DATA_FOUND THEN

    RETURN FALSE;END;

    /

  • 8/22/2019 Pls Ql 4 Sub Programs

    17/32

    CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 17

    Calling Stored Functions from Different Locations

    Functions can be called from different locations through SELECTand DML statements like:

    Column list of SELECT command

    WHERE and HAVING Clause

    ORDER BY, GROUP BY Clauses

    VALUES clause of INSERT command

    SET clause of UPDATE command

    Note: Not all functions can be called from above mentioned locations.

    Rules for Calling a Function through a SQL

  • 8/22/2019 Pls Ql 4 Sub Programs

    18/32

    CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 18

    Rules for Calling a Function through a SQLStatement

    To be callable from SQL statement:

    The function must be stored in database as either stand alonefunction or as a part of a package

    The function can take only IN type of parameters

    The formal parameters and return type of the function must beoracle data types

    The function must not end the current transaction (commit orrollback) or rollback to a savepoint prior to the functionexecution

    The function must not issue any alter session or alter systemcommands

  • 8/22/2019 Pls Ql 4 Sub Programs

    19/32

    CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 19

    Difference between Procedures and Functions

    Procedures Functions

    Execute as a PL/SQL statement Invoked as part of an expression

    Do not contain RETURN clause in theheader

    Must contain a RETURN clause in theheader

    Can return none, one or many valueswith the help of OUT & IN OUTparameters

    Must return a value using the RETURNclause. Can also return one or manyvalues with the help of OUT and INOUT parameters.

  • 8/22/2019 Pls Ql 4 Sub Programs

    20/32

    CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 20

    Referencing Objects from Other Schemas

    To reference objects from other schemas we first need to haveappropriate privileges on the objects

    To refer to objects in schemas other than our own, prefix theobject name with the schema name:

    Schema_name.Object_name

    Example: To get information from the emp table belonging toscott's schema the user HR should use the following command

    SELECT * FROM scott.emp;

    Note: The command will run successfully only if the user HR isgranted SELECT right on Scott's emp table

    To execute a procedure belonging to scotts schema the user HR

    will use the following commandEXECUTE scott.procedure_name

  • 8/22/2019 Pls Ql 4 Sub Programs

    21/32

    CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 21

    Granting Privileges on Subprograms

    The object privileges applicable to subprograms are

    EXECUTE Grants right to execute the subprogram belonging to the schema of

    the other user

    Syntax

    GRANT EXECUTE ON subprogram_name

    TO username[, username.]|PUBLIC;

    Example

    GRANT EXECUTE ON emp_salary_increase TO PUBLIC;

  • 8/22/2019 Pls Ql 4 Sub Programs

    22/32

    CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 22

    Revoking Privileges on Subprograms

    To take back a privilege that is granted to a user

    Syntax

    REVOKE EXECUTE ON subprogram_name FROMUsername[,username..] |PUBLIC;

    Example

    REVOKE EXECUTE ON emp_salary_increase FROM

    itp_jul_01, itp_jul_02;

  • 8/22/2019 Pls Ql 4 Sub Programs

    23/32

    CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 23

    Dropping PROCEDURES and FUNCTIONS

    To Delete a PROCEDURE:

    DROP PROCEDURE ;e.g.

    DROP PROCEDURE emp_salary_increase;

    To Delete a FUNCTION:

    DROP FUNCTION < Functionname >;

    e.g.

    DROP FUNCTION chk_dept;

  • 8/22/2019 Pls Ql 4 Sub Programs

    24/32

    CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 24

    Local Procedures and Functions

    The subprograms can also be defined within the declarativesection of a block. Such subprograms are known as LocalSubprograms

    Local subprograms can also be defined within an anonymousblock

    These subprograms follow the same scope and visibilityrules as any other PL/SQL identifier

    It is only visible in the block in which it is declared

    No other block can call local subprograms, as they are notvisible to any other block

    Local Procedures and Functions within a Stored

  • 8/22/2019 Pls Ql 4 Sub Programs

    25/32

    CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 25

    Local Procedures and Functions within a StoredSubprogram

    CREATE OR REPLACE PROCEDURE emp_pro AS

    CURSOR c_allEmp IS SELECT deptno, ename FROM emp;

    v_dname dept.dname%TYPE;

    -- Local function ,local to the procedure which will return thedept name for an employee

    FUNCTION show_deptname (p_dno dept.deptno%TYPE) RETURN VARCHAR2IS

    v_dname dept.dname%TYPE;

    BEGIN

    SELECT dname INTO v_dname FROM dept WHERE deptno=p_dno;

    RETURN v_dname;

    END show_deptname;

    BEGIN

    FOR v_rec IN c_allEmp LOOP

    v_dname := show_deptname (v_rec.deptno);

    DBMS_OUTPUT.PUT_LINE(v_rec.ename ||' belongs to

    '||v_dname);END LOOP;

    EXCEPTION

    WHEN NO_DATA_FOUND THEN

    DBMS_OUTPUT.PUT_LINE('Wrong departmentnumber');

    END emp_pro;

    Difference between Stand Alone and Local

  • 8/22/2019 Pls Ql 4 Sub Programs

    26/32

    CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 26

    Difference between Stand Alone and LocalSubprograms

    Stand Alone Subprograms Local Subprograms

    Stored Subprograms can be

    called from any block submittedby a user that has EXECUTEprivilege on the subprogram

    Local subprograms can be called

    from only the block containingthe subprogram

    The subprogram and the callingblock can be maintained

    separately

    The Subprogram and the callingblock are part of the same

    program unit

    Stand-Alone storedsubprograms cannot beoverloaded

    Local subprograms can beoverloaded

  • 8/22/2019 Pls Ql 4 Sub Programs

    27/32

    CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 27

    Methods of Passing Parameters

    The various methods available for passing parameters tosubprograms are:

    Positional

    Pass actual parameters in the same order as formal parameters

    Named

    Pass actual parameters in arbitrary order by associating eachwith its corresponding formal parameter using special syntax

    (=>) Combination

    Pass at least the first actual parameters as positional and therest as named

    Note: While using combination the positional parametersshould be passed first

  • 8/22/2019 Pls Ql 4 Sub Programs

    28/32

    CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 28

    Methods of PassingParameters: Example

    CREATE TABLE employee AS SELECT ename, sal, comm

    FROMemp;TRUNCATE TABLE employee;

    CREATE OR REPLACE PROCEDURE add_employee

    (p_name IN emp.ename%TYPE DEFAULT 'unknown',

    p_sal IN emp.sal%TYPE DEFAULT 1000,p_comm IN emp.comm%TYPE DEFAULT 0)

    IS

    BEGIN

    INSERT INTO employee (ename,sal,comm)

    VALUES( p_name, p_sal,p_comm);COMMIT;

    END add_employee;

    /

  • 8/22/2019 Pls Ql 4 Sub Programs

    29/32

    CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 29

    Methods of PassingParameters: Example

    BEGIN

    add_employee ;

    add_employee ('SMITH', 2000,600);

    add_employee (p_sal=> 6000,p_comm=>200, p_name

    =>'STEVE');

    add_employee (p_sal =>4000) ;

    add_employee('MARK',p_comm=>200, p_sal=> 6000);

    END;

    /

    SELECT * FROM employee;

    Note: All the positional parameters should precede the namedparameters in a subprogram call.

  • 8/22/2019 Pls Ql 4 Sub Programs

    30/32

    CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 30

    Data Dictionary View

    USER_SOURCE

    Is used to obtain the text of a stored procedure or a storedfunction

    USER_ERRORS Is used to find out the compilation errors in the subprogram,

    currently getting compiled

    One can use the SQL*Plus command SHOW ERRORS, insteadof firing a SELECT query on USER_ERRORS

    USER_OBJECTS Is used to get the details of all the objects created in a

    particular schema

    USER_PROCEDURES

    Is used to get the details of all procedures in that usersschema

  • 8/22/2019 Pls Ql 4 Sub Programs

    31/32

    CONFIDENTIAL Copyright 2008 Tech Mahindra Limited 31

    Summary

    In this session, we have covered:

    Need for subprograms

    Creating Stored Procedures Invoking stored procedures from SQL*Plus and PL/SQL Block

    Subprogram Parameter Modes IN, OUT and IN OUT

    Creating Stored Functions

    Calling Stored Functions from different locations

    Privileges related to functions and procedures

    Dropping procedures and functions

    Local Procedures and Functions within a stored subprogram

    Methods of passing Parameters

    Data dictionary views related to subprograms

    USER_OBJECTS USER_SOURCE

    USER_PROCEDURES

    USER_ERRORS

  • 8/22/2019 Pls Ql 4 Sub Programs

    32/32

    Thank You