Pls QL 4 Sub Programs

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 32

Procedures and Functions

Objectives
At the end of this session, you will be able to:
Understand subprograms and their need Comprehend the difference between stored and unstored subprograms 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

CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

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

CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

Subprograms in PL/SQL
PL/SQL blocks are anonymous, can not be called from other PL/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

CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

Syntax for Creating a Procedure


Stored Procedure
A stored procedure is a named PL/SQL block that performs an action. It is stored in the database as a database object for repeated execution.

CREATE [ OR REPLACE ] PROCEDURE proc_name[(argument [mode] data type, argument [mode] data type,)]
-- PROCEDURES and FUNCTIONS may or may not accept arguments IS Local PL/SQL variable declarations BEGIN Define action performed by the procedure EXCEPTION Handle exceptions, if any END [ proc_name]; /

CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

RAISE_APPLICATION_ERROR Procedure
This procedure is used to display error messages along with error numbers Example RAISE_APPLICATION_ERROR(-20001, Invalid Employee); Note:
When called, RAISE_APPLICATION_ERROR ends a subprogram, rolls back any database changes it made, and returns a user-defined error message to the application Error numbers should be between -20000 and -20999

CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

Parameters Modes in Procedures and Functions


Formal parameters can have three modes IN, OUT or IN OUT which decides the behavior of parameters
IN Default parameter mode Value is passed into subprograms OUT Must be specified Value is returned to the calling environment IN OUT Must be specified Value is passed into subprogram and formatted/changed value is returned to the calling environment Formal parameter acts as a initialized variable, as the calling environment will pass a value for it. Actual parameter must be a variable
CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

Formal parameter acts as a constant inside a subprogram Actual parameter can be an expression, constant or initialized variable

Formal parameter acts as a uninitialized variable, as the subprogram will assign value to it Actual parameter must be a variable

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 <2000 THEN UPDATE emp SET sal = sal+vsal * 0.1 WHERE empno = p_eno; END IF; -- An exception handler to raise error if empno is not valid EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE (Empno does not exist); END raise_salary; /

CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

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 command e.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;

CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

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; EXCEPTION WHEN NO_DATA_FOUND THEN RAISE_APPLICATION_ERROR(-20001, Employee does not exist); END query_emp;
/

CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

10

Invoking a Procedure Having OUT Parameters


SQL> VARIABLE SQL> VARIABLE name salary VARCHAR2(20) NUMBER

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

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

CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

11

IN OUT Parameter: Example


CREATE OR REPLACE PROCEDURE emp_salary_increase1 (p_salary IN OUT emp.sal%TYPE) IS BEGIN 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 THEN DBMS_OUTPUT.PUT_LINE(SQLERRM); END; /
CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

12

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

CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

13

Syntax for Creating a Function


A function is a named PL/SQL block that performs a task and returns a value to the calling environment. Syntax:
CREATE [ OR REPLACE ] FUNCTION function_name [( argument [mode] data type, argument [mode] data type )] RETURN data type IS Local PL/SQL variable declarations BEGIN Define task performed by the function and return result using RETURN statement EXCEPTION Handle exceptions if any END [ function_name];

CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

14

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 WHERE empno = p_eno; RETURN (v_sal * 0.1); EXCEPTION WHEN NO_DATA_FOUND THEN RETURN -1; END;

emp

CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

15

Functions in PL/SQL
Example 2

CREATE OR REPLACE FUNCTION chk_dept (p_deptno dept.deptno%TYPE) RETURN BOOLEAN IS v_deptno dept.deptno%type; BEGIN SELECT deptno into v_deptno FROM dept WHERE deptno = p_deptno; RETURN TRUE; EXCEPTION WHEN NO_DATA_FOUND THEN RETURN FALSE; END; /

CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

16

Calling Stored Functions from Different Locations


Functions can be called from different locations through SELECT and 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.

CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

17

Rules for Calling a Function through a SQL Statement To be callable from SQL statement:
The function must be stored in database as either stand alone function 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 be oracle data types The function must not end the current transaction (commit or rollback) or rollback to a savepoint prior to the function execution The function must not issue any alter session or alter system commands

CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

18

Difference between Procedures and Functions


Procedures
Execute as a PL/SQL statement

Functions
Invoked as part of an expression

Do not contain RETURN clause in the header

Must contain a RETURN clause in the header

Can return none, one or many values with the help of OUT & IN OUT parameters

Must return a value using the RETURN clause. Can also return one or many values with the help of OUT and IN OUT parameters.

CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

19

Referencing Objects from Other Schemas


To reference objects from other schemas we first need to have appropriate privileges on the objects To refer to objects in schemas other than our own, prefix the object name with the schema name: Schema_name.Object_name Example: To get information from the emp table belonging to scott'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 is granted SELECT right on Scott's emp table
To execute a procedure belonging to scotts schema the user HR will use the following command EXECUTE scott.procedure_name

CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

20

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;

CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

21

Revoking Privileges on Subprograms To take back a privilege that is granted to a user


Syntax REVOKE EXECUTE ON subprogram_name FROM Username[,username..] |PUBLIC; Example REVOKE EXECUTE ON emp_salary_increase FROM itp_jul_01, itp_jul_02;

CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

22

Dropping PROCEDURES and FUNCTIONS


To Delete a PROCEDURE: DROP PROCEDURE <Procedurename>; e.g. DROP PROCEDURE emp_salary_increase; To Delete a FUNCTION: DROP FUNCTION < Functionname >; e.g. DROP FUNCTION chk_dept;

CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

23

Local Procedures and Functions


The subprograms can also be defined within the declarative section of a block. Such subprograms are known as Local Subprograms

Local subprograms can also be defined within an anonymous block


These subprograms follow the same scope and visibility rules 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 not visible to any other block

CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

24

Local Procedures and Functions within a Stored Subprogram


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 the dept name for an employee FUNCTION show_deptname (p_dno dept.deptno%TYPE) RETURN VARCHAR2 IS 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 department number'); END emp_pro;
CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

25

Difference between Stand Alone and Local Subprograms


Stand Alone Subprograms Stored Subprograms can be called from any block submitted by a user that has EXECUTE privilege on the subprogram The subprogram and the calling block can be maintained separately Stand-Alone stored subprograms cannot be overloaded Local Subprograms Local subprograms can be called from only the block containing the subprogram The Subprogram and the calling block are part of the same program unit Local subprograms can be overloaded

CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

26

Methods of Passing Parameters


The various methods available for passing parameters to subprograms are:
Positional Pass actual parameters in the same order as formal parameters Named Pass actual parameters in arbitrary order by associating each with its corresponding formal parameter using special syntax (=>) Combination Pass at least the first actual parameters as positional and the rest as named

Note: While using combination the positional parameters should be passed first

CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

27

Methods of Passing Parameters: Example


CREATE TABLE employee AS SELECT ename, sal, comm FROM emp; 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; /
CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

28

Methods of Passing Parameters: 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 named parameters in a subprogram call.

CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

29

Data Dictionary View


USER_SOURCE
Is used to obtain the text of a stored procedure or a stored function

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, instead of 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 users schema

CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

30

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

CONFIDENTIAL Copyright 2008 Tech Mahindra Limited

31

Thank You

You might also like