280 likes | 455 Views
PL/SQL Subprograms. Session - IV. What are SubPrograms?. Subprograms are named PL/SQL block that can take parameters and be invoked. Two Types of Subprogram. PROCEDURES FUNCTIONS. Where are They Allowed?. Subprograms can be defined using any ORACLE tool that supports PL/SQL
E N D
PL/SQL Subprograms Session - IV
What are SubPrograms?. • Subprograms are named PL/SQL block that can take parameters and be invoked. Two Types of Subprogram. • PROCEDURES • FUNCTIONS
Where are They Allowed? • Subprograms can be defined using any ORACLE tool that supports PL/SQL • Must be declared at the end of a declarative section after all other program objects.
E.g.:- Declare PROCEDURE TEST IS DBMS_OUTPUT.PUT_LINE(‘Testing’); End; Begin Test; End;
Procedure • Is Subprogram that performs a specific action. • Has two parts the specification and body.
Specification begins with the keyword PROCEDURE and end with Procedure Name. • Parameter Declaration are optional.
Procedure body begins with the keyword END followed by an optional Procedure Name.
The Procedure body has 3 Parts • Declarative Part • Executable part • Optional Exception-Part
Declarative Part Contains Local Declarations which are placed between IS and BEGIN.
Declare Procedure Pn is enam varchar(15); Begin Select ename INTO enam from emp where empno=7369; DBMS_OUTPUT.PUT_LINE(ENAM); End;
Parameter Modes • IN • OUT • IN OUT
IN • Lets you pass value to the subprogram being called.
OUT • Lets you pass return values to the caller of a Subprogram
IN OUT • Lets you pass initial values to the subprogram and return updated values to the caller.
Function • A Function is a Subprogram that computes a value. Functions and Procedures are structured alike, Except that functions have a RETURN clause.
Function CREATE OR REPLACE FUNCTION FUN (ID NUMBER) RETURN CHAR IS NAME EMP.ENAME%TYPE; BEGIN SELECT ENAME INTO NAME FROM EMP WHERE EMPNO=ID; RETURN(NAME); END;
CREATE OR REPLACE FUNCTION F1(N NUMBER) RETURN NUMBER IS SALARY EMP.SAL%TYPE; BEGIN SELECT SAL INTO SALARY FROM EMP WHERE EMPNO=N; RETURN SALARY; END;
DECLARE A number(30); BEGIN A:=F1(&N); DBMS_OUTPUT.PUT_LINE(A); END; ( OR ) SELECT F1(7369) from dual;
PACKAGES Is an encapsulated collection of related program objects stored together in the database.
Program Objects are :- • Procedures • Functions • Variables • Constants • Cursors • Exceptions
CREATE PACKAGES There are Two Distinct Steps to Create Package 1. PACKAGE SPECIFICATION 2. PACKAGE BODY
PACKAGE SPECIFICATION • CREATE PACKAGE Command <> can declare Program Objects i.e.. Procedures ,Functions etc..
PACKAGE BODY • CREATE PACKAGE BODY Command can declare and define Program Objects
CREATE OR REPLACE PACKAGE P56 IS PROCEDURE P4(ENO NUMBER); END;
CREATE OR REPLACE PACKAGE BODY P56 IS PROCEDURE P4(ENO NUMBER) IS DESG EMP.JOB%TYPE; BEGIN SELECT JOB INTO DESG FROM EMP WHERE EMPNO=ENO; DBMS_OUTPUT.PUT_LINE(DESG); END P4; END P56;