Oracle 9i

Knowledge Level: Basic / Intermediate

2.0 PL/SQL Fundamentals : Overview
Introduction:
PL/SQL provides programming facility to the users in Oracle to implement complex business logic.

Objective:
After completing this module, you will be able to,
1 .PL/SQL Features 2. PL/SQL Block Structures 3. Identifiers 4. Variables 5. Data Types

©Copyright 2004, Cognizant Academy, All Rights Reserved

2

2.0 PL/SQL Fundamentals : Overview
6. Composite Types 7. PL/SQL Statements 8. PL/SQL statements 9. Oracle Supplied Packages 10. Expressions and Operators 11. Conditional and Loop Constructs

©Copyright 2004, Cognizant Academy, All Rights Reserved

3

Control Structures (IF-THEN-ELSE) . Cognizant Academy.Object types and methods ©Copyright 2004.Procedures and Functions .Variables and types .PL/SQL Features Features of PL/SQL ‡ PL/SQL stands for Procedural Language/SQL ‡ PL/SQL extends SQL by adding constructs found in other procedural languages . All Rights Reserved 4 .

‡ PL/SQL Statement DECLARE l_date DATE. END.PL/SQL Features ifference between SQL and PL/SQL ‡ SQL Statement SQL> SELECT sysdate FROM DUAL. Cognizant Academy. All Rights Reserved 5 . ©Copyright 2004. BEGIN SELECT sysdate into l_date from dual.

All Rights Reserved 6 . Cognizant Academy.PL/SQL Features Need of PL/SQL ‡ Procedural Language/Structured Query Language is an extension to SQL ‡ PL/SQL provides programming facility to the users ‡ Set of instructions that can be stored in the server as Database Objects in compiled form ©Copyright 2004.

All Rights Reserved 7 .PL/SQL Features How Pl/SQL Works ‡ Blocks of Pl/SQL statements are translated by the PL/SQL engine that can reside either in the client or at the server side ‡ It divides the SQL statements from PL/SQL block and sends them to SQL STATEMENT EXECUTOR ‡ The output finally comes to the Client end ©Copyright 2004. Cognizant Academy.

PL/SQL Features PL/SQL Architecture ©Copyright 2004. Cognizant Academy. All Rights Reserved 8 .

PL/SQL Features PL/SQL Architecture ©Copyright 2004. Cognizant Academy. All Rights Reserved 9 .

A statement is terminated with a semicolon (. Cognizant Academy. Declarative part. not with the physical end of a line ‡ It has three parts.PL/SQL Block Structure ‡ PL/SQL is a block structured language ‡ PL/SQL program is made up of a series of statements.). an Executable part and an Exception Handling part ©Copyright 2004. All Rights Reserved 10 .

error handling statements */ END. cursors and types */ BEGIN /* Executable section .PL/SQL variables.PL/SQL Block Structure ‡ Syntax DECLARE /*Declarative Section . ©Copyright 2004. All Rights Reserved 11 .procedural and SQL statements */ EXCEPTION /* Exception handling section . Cognizant Academy.

All Rights Reserved 12 .PL/SQL Block Structure Anonymous Blocks Declare /* variables*/ Begin /*SQL statements */ Exception /* Error handling */ End. Cognizant Academy. ©Copyright 2004.

©Copyright 2004.PL/SQL Block Structure Named Block ‡ Replace DECLARE keyword with CREATE OR REPLACE ‡ Example Create or Replace Procedure Validate_Date AS /* variables*/ Begin /*SQL statements */ Exception /* Error handling */ End Validate_Date. Cognizant Academy. All Rights Reserved 13 .

Identifiers ‡ Must start with a letter ‡ Up to 30 characters in length ‡ May include a $ (dollar sign). and # (pound sign) ‡ Cannot contain embedded spaces ©Copyright 2004. All Rights Reserved 14 . Cognizant Academy. _ (underscore).

Variables ‡ Variables are memory locations. All Rights Reserved 15 . Cognizant Academy. or the contents of a variable can be inserted into the database ‡ The variables are declared in the declarative section of the block ‡ Every variable has a specific type which describes what kind of information it can store ©Copyright 2004. which can store data values ‡ Information from database can be assigned to a variable.

v_NumberSeats NUMBER := 45.Variables Variable Declarations ‡ Declaration Syntax variable_name type [CONSTANT][NOT NULL][:=value] ‡ Example DECLARE v_Description VARCHAR2(50). ©Copyright 2004. v_Counter BINARY_INTEGER DEFAULT 0. All Rights Reserved 16 . Cognizant Academy.

Cognizant Academy. All Rights Reserved 17 . END.2).Variables Variable Scope DECLARE v_number NUMBER(3. BEGIN Scope of v_Character END. BEGIN « DECLARE Scope of v_number « v_Character VARCHAR2(10). ©Copyright 2004.

All Rights Reserved Records PL/SQL Tables 18 .Data Types Data Types Scalar Datatypes BINARY_INTEGER DEC DECIMAL DOUBLE PRECISION FLOAT INT INTEGER NATURAL NUMBER NUMERIC POSITIVE REAL SMALLINT CHAR CHARACTER LONG LONG RAW ROWID STRING VARCHAR VARCHAR2 DATE BOOLEAN Composite Dataypes ©Copyright 2004. Cognizant Academy.

All Rights Reserved 19 . developer must define the type. then declare variables of that type ‡ To refer to a field within a record . dot notation is used ©Copyright 2004.Composite Types PL/SQL Record ‡ A record is similar to ³C´ structure ‡ Record provide a way to deal with separate but related variables as Unit ‡ To use. Cognizant Academy.

LastName VARCHAR2(20)). All Rights Reserved 20 . Cognizant Academy. v_FirstName VARCHAR2(20). v_studentInfo t_StudentRec. v_LastName VARCHAR2(20). ©Copyright 2004.Composite Types PL/SQL Record ‡ Following declarative section can be replaced by PL/SQL Record ‡ Example DECLARE v_StudentID NUMBER(5). DECLARE TYPE t_studentRec IS RECORD ( StudentID NUMBER(5). FirstName VARCHAR2(20).

Cognizant Academy. REC2 EMP%ROWTYPE ©Copyright 2004.Composite Type PL/SQL Record ‡ Use the %ROWTYPE attribute to declare a record based upon a collection of database columns from a table or view ‡ The fields within the record take their names and data types from the columns of the table or view ‡ Declare the record in the DECLARE section along with any other required variables and constants ‡ Example DECLARE REC1 EMP%ROWTYPE. All Rights Reserved 21 .

©Copyright 2004. ± Data type can be varchar2. Number.Composite Type PL/SQL Table ‡ A table is like ³C´ array ‡ Syntax Type array_name is TABLE OF data_type INDEX BY BINARY_INTEGER. Table%Rowtype ‡ Example TYPE string_name IS TABLE OF VARCHAR2(30) INDEXED BY BINARY_INTEGER. Cognizant Academy. All Rights Reserved 22 . employee_name_table string_name. Table. t_temp array_name.column%TYPE.

Composite Type PL/SQL Table ‡ The number of rows in a Pl/SQL table can increase dynamically ‡ A Table can have only one primary key(BINARY_INTEGER) and a column ‡ The individual element in the PL/SQL table is accessed by tablename(index) ©Copyright 2004. Cognizant Academy. All Rights Reserved 23 .

Cognizant Academy. All Rights Reserved 24 .delete(i) : Remove i th row from PL/SQL table ‡ table.Composite Type ‡ table.LAST : Return index of the last row ©Copyright 2004.count : Return number of rows ‡ table.delete : Remove from PL/SQL table ‡ table.FIRST : Return the index of the first row ‡ table.

‡ Multiple column values can be assigned to equal number of memory variables using single INTO SELECT ENAME. ©Copyright 2004. MEMSAL FROM EMP WHERE EMPNO=101176.PL/SQL Statements Statements in PL/SQL ‡ The INTO clause must be used to store a table column value into a variable declared in the DECLARATION section of PL/SQL block SELECT ENAME INTO MEMNAME FROM EMP WHERE EMPNO=101176. Cognizant Academy. All Rights Reserved 25 . SAL INTO MEMNAME.

All Rights Reserved 26 . Cognizant Academy.Oracle Supplied Packages ‡ Packaged procedures are supplied with Oracle to enable PL/SQL access SQL features or enhance the functionality of the database ‡ The names of the packages are ± ± ± ± ± ± DBMS_ALERT DBMS_DDL DBMS_DESCRIPTION DBMS_JOB DBMS_LOCK DBMS_OUTPUT ©Copyright 2004.

For example . Cognizant Academy. the expression µHello ¶||¶World¶ evaluates to µHello World¶. separated by operators. All Rights Reserved 27 . ©Copyright 2004.Expressions and Operators ‡ An expression is a sequence of variables and literals. ‡ The most basic operator is assignment ‡ Syntax variable := expression ‡ Variable is PL/SQL variable and expression is PL/SQL expression ‡ PL/SQL expression is: 3 + 5 * 7 ‡ Concatenation operator ( || ) attaches two or more strings together.

Cognizant Academy. All Rights Reserved 28 .Expressions and Operators ©Copyright 2004.

Conditional and Loop Constructs
PL/SQL Control Structures
‡ IF-THEN-ELSE ‡ LOOPS ‡ WHILE LOOPS ‡ FOR LOOPS

©Copyright 2004, Cognizant Academy, All Rights Reserved

29

Conditional and Loop Constructs
IF-THEN-ELSE
‡ Syntax
IF boolean_statements1 THEN sequence_of_statements1; ELSIF boolean_statements2 THEN sequence_of_statements2; ELSE sequence_of_statements3; END IF;

©Copyright 2004, Cognizant Academy, All Rights Reserved

30

Conditional and Loop Constructs
Example
DECLARE v_NumberSeats rooms.number_seats%TYPE; v_Comment VARCHAR2(35); BEGIN /* Retrieve the number of seats in the room identified by ID 99999. Store the result in v_NumberSeats. */ SELECT INTO FROM WHERE number_seats v_NumberSeats rooms room_id = 99999;

©Copyright 2004, Cognizant Academy, All Rights Reserved

31

END. < 100 THEN := 'A little bigger'. All Rights Reserved 32 . / 50 THEN := 'Fairly small'. := 'Lots of room'. Cognizant Academy. ©Copyright 2004.Conditional and Loop Constructs IF v_NumberSeats < v_Comment ELSIF v_NumberSeats v_Comment ELSE v_Comment END IF.

All Rights Reserved 33 . sequence of statements will be executed infinitely.since the loop has no stopping condition. END LOOP. Cognizant Academy. to break the loop the syntax is: EXIT [WHEN condition]. ©Copyright 2004. So.Conditional and Loop Constructs LOOPS ‡ Syntax LOOP sequence_of_statements.

Conditional and Loop Constructs WHILE Loop ‡ Syntax WHILE condition LOOP sequence_of_statements. END LOOP. ©Copyright 2004. Cognizant Academy. All Rights Reserved 34 .

Cognizant Academy. ©Copyright 2004. END LOOP.¶Loop Index¶). ‡ Example BEGIN FOR v_counter IN 1 . high_bound LOOP sequence_of_statements. All Rights Reserved 35 . END..Conditional and Loop Constructs FOR Loop ‡ Syntax FOR loop_counter IN [REVERSE] low_bound .. 50 LOOP INSERT INTO temp_table values (v_counter. END LOOP.

PL/SQL Fundamentals : Summary ‡ PL/SQL extends SQL by adding constructs found in other procedural languages like conditional constructs. ‡ Composite Types can be PL/SQL Record and PL/SQL Tables ‡ A Record is like a µC¶ structure. The %ROWTYPE attribute is used to declare a record based upon a collection of database columns from a table or view ‡ A table is like a µC¶ array. All Rights Reserved 36 . functions etc. A Table can have only one primary key(BINARY_INTEGER) and a column ©Copyright 2004. ‡ Data types can be Scalar types and Composite types. variables data types. Cognizant Academy. looping. procedures.

----Total for Deptno 10 dname: Accounts Ename Job ------- Sal ©Copyright 2004. The report should look like this. DEPT No: 10 Deptno Emono --.: Quiz ‡ Write a PL/SQL block to print the Department wise Employee Details.------. All Rights Reserved 37 . Cognizant Academy. with Total for each department as well as Grand Total.

Cognizant Academy. All Rights Reserved 38 .©Copyright 2004.

Open Cursors 3. you will be able to. Oracle exceptions handlers are used to trap runtime errors. Cursor Attributes ©Copyright 2004. The implicit cursor is used by Oracle server to test and parse the SQL statements and the explicit cursors are declared by the programmers. 1 . Objective: After completing this module. All Rights Reserved 39 .3.0 Cursors and Exceptions : Overview Introduction: A SQL cursor is a private Oracle SQL working area. Fetch Cursor 4.Understand Cursors 2. Close Cursor 5. Cognizant Academy.

Examples of Cursors 7. Understand Exceptions 8. Cognizant Academy. PRAGMA EXCEPTION_INIT 11. All Rights Reserved 40 .3. RAISE_APPLICATION_ERROR ©Copyright 2004. Pre-defined Exception 9 User-defined Exceptions 10.0 Cursors and Exceptions : Overview 6.

All Rights Reserved 41 .Cursors ‡ The cursor is a handle or pointer to the context area. The context area is a memory allocation that Oracle allocate to process a SQL statements ‡ Cursor Types ± Implicit ± Explicit ‡ An Implicit cursor is used for all other SQL statements ‡ Implicit Cursors gives less programmatic control ‡ In explicit cursor the cursor name is explicitly attached to a select statement ©Copyright 2004. Cognizant Academy.

Cognizant Academy. All Rights Reserved 42 .Cursors The four PL/SQL steps necessary for explicit cursor processing are as follows: ‡ Declare the cursor ‡ Open the cursor ‡ Fetch the results into PL/SQL variables ‡ Close the cursor ©Copyright 2004.

‡ A cursor without parameters CURSOR comp IS SELECT compid FROM company. All Rights Reserved 43 . ‡ A cursor with parameters CURSOR comp (mcompid IN NUMBER) IS SELECT name FROM company WHERE compid = mcomid.Declaring a Cursor ‡ ‡ To use a cursor. Cognizant Academy. it must be declared first Syntax CURSOR cursor_name IS SELECT_statement. ©Copyright 2004.

All Rights Reserved 44 . ©Copyright 2004. i_course classes.Declaring a Cursor Parameterized Cursors ‡ A parameterized cursor takes arguments. Cognizant Academy.course%TYPE ) IS SELECT WHERE and * FROM CLASSES department = i_department course = i_course. ‡ Example DECLARE CURSOR Class_cur ( i_dept classes.department%TYPE.

All Rights Reserved 45 . ‡ A cursor can only be opened if it is closed IF NOT Stud_cur%ISOPEN THEN OPEN Stud_cur. Cognizant Academy. ©Copyright 2004. PL/SQL executes the query for the cursor Syntax OPEN cursor_name.Opening a Cursor ‡ ‡ When a Cursor is opened. END IF. ‡ The following things happen if the cursor is opened: ± The values of the bind variables are examined ± Based on the bind variable the active set is determined ± The active set pointer is set to the first row.

each FETCH will return successive rows in the active set. or FETCH cursor_name INTO PL/SQL_record. ‡ The %NOTFOUND attribute is used to determine when the active set has been retrieved. FETCH cursor_name INTO list_of_variables. the active set pointer is increased to next row ‡ Thus. ©Copyright 2004. Cognizant Academy. ‡ After each FETCH.Fetching Cursor Fetching from a Cursor ‡ It has two forms. until the entire set is returned. All Rights Reserved 46 .

Closing a Cursor ‡ It tell PL/SQL that the program is finished with the cursor. Cognizant Academy. ©Copyright 2004. All Rights Reserved 47 . and the resource associated with it can be freed ‡ Syntax CLOSE cursor_name.

‡ %NOTFOUND : TRUE if the FETCH doesn¶t return rows.Cursor Attributes ‡ %FOUND : TRUE if the FETCH return rows. ‡ %ROWCOUNT : Return the number of rows fetched by the cursor so far ‡ %ISOPEN : Returns TRUE if the cursor is open ©Copyright 2004. All Rights Reserved 48 . Cognizant Academy. otherwise FALSE. otherwise FALSE.

last_name FROM students WHERE major = v_Major.Cursor Example DECLARE /* Output variables to hold the results of the query */ v_StudentID students. ©Copyright 2004.last_name%TYPE. All Rights Reserved 49 .major%TYPE := 'Computer Science'.first_name%TYPE. v_LastName students. Cognizant Academy. first_name. v_FirstName students. /* Cursor declaration */ CURSOR c_Students IS SELECT id. /* Bind variable used in the query */ v_Major students.id%TYPE.

exit the loop */ EXIT WHEN c_Students%NOTFOUND. /* Free resources used by the query */ CLOSE c_Students. v_LastName. v_FirstName. END LOOP. All Rights Reserved 50 . / ©Copyright 2004.Cursor Example BEGIN /* Identify the rows in the active set. Cognizant Academy. END. LOOP /* Retrieve each row of the active set into PL/SQL variables */ FETCH c_Students INTO v_StudentID. /* If there are no more rows to fetch. and prepare for further processing of the data */ OPEN c_Students.

Cognizant Academy.Exceptions ‡ Oracle raises ERRORS whenever any abnormal situation arises in a PL/SQL block and performs an illegal termination of the execution of the program ‡ PL/SQL traps and responds to errors using an architecture of EXCEPTION handler ©Copyright 2004. All Rights Reserved 51 .

to handle the exception ‡ The control never returns to that block after you finish handling the exception. control is passed to the enclosing block. if one exists. All Rights Reserved 52 . whether a system error or an application error. Cognizant Academy. if any ©Copyright 2004. Instead. an exception is raised ‡ This halts the processing in the current PL/SQL block's execution and control is transferred to the separate exception section of the program.Exceptions ‡ Occurrence of any error in PL/SQL.

Exceptions ‡ When an exception is raised . ©Copyright 2004. END. The exception section consists of handlers for all the exceptions EXCEPTION WHEN exception_name THEN sequence_of_statements1. control passes to the exception section of the block. Cognizant Academy. All Rights Reserved 53 . WHEN exception_name THEN sequence_of_statements1.

Exceptions
Exceptions types,
‡ Predefined Exception ‡ User Defined Exception

©Copyright 2004, Cognizant Academy, All Rights Reserved

54

Predefined Exceptions
‡ Some exceptions are already defined in Oracle called the predefined exception ‡ Mostly they are generated with the SELECT statement ‡ They are raised implicitly at runtime ‡ Every exception is associated with a error code ‡ These exceptions are already defined in the STANDARD package (an Oracle supplied package) ‡ The when clause is used to test a system defined exception

©Copyright 2004, Cognizant Academy, All Rights Reserved

55

Predefined Exceptions
‡ CURSOR_ALREADY_OPEN (ORA ±6511) DUP_VAL_ON_INDEX( ORA00001) INVALID_CURSOR(ORA-01001) INVALID_NUMBER(ORA-01722) ‡ ‡ ‡ ‡ LOGIN_DENIED(ORA-1017) ‡ NO_DATA_FOUND(ORA-01403) ‡ NOT_LOGGED_ON(ORA-01012)
©Copyright 2004, Cognizant Academy, All Rights Reserved 56

‡ ‡

PROGRAM_ERROR(ORA-06501) ROWTYPE_MISMATCH( STORAGE_ERROR(ORA-06500) TIMEOUT_ON_RESOURCE(ORA00051) TOO_MANY_ROWS(ORA-01422) VALUE_ERRORS(ORA_06502) ZERO_DIVIDE(ORA-01476)

‡

‡ ‡

‡ ‡

©Copyright 2004. V_ERR_TEXT VARCHAR2(255) EXCEPTION WHEN NO_DATA_FOUND THEN V_ERR_CODE := SQLCODE. All Rights Reserved 57 .Predefined Exceptions Exception Functions ‡ SQLCODE : Returns the numeric value for the error code ‡ SQLERRM : Returns the message associated with the error number ‡ Example DECLARE V_ERR_CODE NUMBER. Cognizant Academy. V_ERR_TEXT := SQLERRM.

EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT. Cognizant Academy.ENAME%TYPE. All Rights Reserved 58 .Predefined Exceptions ‡ Example DECLARE MEMNAME EMP.PUT_LINE(MEMNAME).PUT_LINE(µNo Such Employee¶). DBMS_OUTPUT. ©Copyright 2004. BEGIN SELECT ENAME INTO MEMNAME FROM EMP WHERE EMPNO = &INPUT_EMPNO. END.

Cognizant Academy. All Rights Reserved 59 . ©Copyright 2004.User Defined Exception ‡ Oracle allows user to raise their own exception in PL/SQL block. Such exceptions are called User Defined Exception ‡ They are to be declared in the Declaration Section and should be explicitly raised using the RAISE statement ‡ Syntax DECLARE e_TooManyStudents EXCEPTION.

N NUMBER(3). END_IF.PUT_LINE(µException Raised¶). All Rights Reserved 60 .User Defined Exception Example DECLARE EX1 EXCEPTION. Cognizant Academy. END. IF N > 10 THEN RAISE EX1. ©Copyright 2004. ELSE DBMS_OUTPUT.PUT_LINE(µNo Exception¶). EXCEPTION WHEN EX1 THEN DBMS_OUTPUT. BEGIN N:=&NUM.

All Rights Reserved 61 . Cognizant Academy.PRAGMA EXCEPTION_INIT ‡ Some uncommon predefined errors numbers exists that does have names ‡ Oracle allows to associate a user-defined name with a predefined error number( Oracle Error) ‡ A pragma called EXCEPTION_INIT instructs the compiler to associate or initialize a programmer-defined exception with a specific Oracle error number ©Copyright 2004.

‡ Example DECLARE MYEXP EXCEPTION. Cognizant Academy. PRAGMA EXCEPTION_INIT(MYEXP.PRAGMA EXCEPTION_INIT ‡ It is associated with a predefined number in the declarative part ‡ Syntax PRAGMA EXCEPTION_INIT( EXCEPTION. -1422). All Rights Reserved 62 . ERROR_NUMBER). ©Copyright 2004.

All Rights Reserved 63 . Cognizant Academy.RAISE_APPLICATION_ERROR ‡ The RAISE_APPLICATION_ERROR procedure to communicate application-specific errors from the server side (usually a database trigger) to the client-side application ‡ This built-in procedure is the only mechanism available for communicating a server-side. programmer-defined exception to the client side in such a way that the client process can handle the exception ‡ Error number should be of the range between ±20000 and ±20999 ©Copyright 2004.

'). ©Copyright 2004.RAISE_APPLICATION_ERROR ‡ Error messages should be less than 512 characters ‡ Syntax RAISE_APPLICATION_ERROR( error_number in NUMBER. All Rights Reserved 64 . Cognizant Academy. error_msg in VARCHAR2). END IF. ‡ Example IF age < 18 THEN RAISE_APPLICATION_ERROR (-20001. Must be eighteen years of age.

Cursors and Exceptions : Summary ‡ A SQL cursor is a private Oracle SQL working area. Cognizant Academy. ‡ The implicit cursor is used by Oracle server to test and parse the SQL statements ‡ Implicit Cursors gives less programmatic control ‡ An Implicit cursor is used for all other SQL statements ‡ Explicit cursors are declared by the programmers ‡ In explicit cursor the cursor name is explicitly attached to a select statement ©Copyright 2004. All Rights Reserved 65 .

Fetching and Closing cursor ‡ Oracle raises ERRORS whenever any abnormal situation arises in a PL/SQL block and performs an illegal termination of the execution of the program ‡ PL/SQL traps and responds to errors using an architecture of EXCEPTION handler ‡ Pre-defined exceptions are already defined in the STANDARD package ‡ Exceptions can be pre-defined(built-in) and user-defined ©Copyright 2004. All Rights Reserved 66 .Cursors and Exceptions : Summary ‡ Explicit cursor handling requires Declaring. Opening. Cognizant Academy.

: Quiz ‡ Create a cursor to print empno. All Rights Reserved 67 . Increment amount depends on the day of joining Day of Joining Friday Wednesday Thursday For all others Increment in % 20 18 17 15 ©Copyright 2004. Cognizant Academy. hiredate and the increment amount for all employees. job. ename. sal.

All Rights Reserved 68 . Cognizant Academy.©Copyright 2004.

objects.0 Procedures. All Rights Reserved 69 . Functions returns a scalar value and PL/SQL procedures return nothing. Passing Parameters 4. and subprograms Objective: After completing this module. Both can take zero or more number of parameters as input or output. A package is a database object that groups logically related PL/SQL types. you will be able to. Creating Functions 5. Cognizant Academy. Understand Procedures 2. Implement Packages ©Copyright 2004. 1 . Functions and Packages : Overview Introduction: PL/SQL procedures and functions are compiled database objects. Creating Parameters 3.4.

Cognizant Academy. All Rights Reserved 70 . Specification and Body ± Specification: This section begins with the keyword Procedure followed by its name and Parameter list(optional) ± Body: Procedure Body begins with the keyword IS/AS and ends with the keyword END followed by the procedure name(optional) ©Copyright 2004. which can perform a specific task when invoked explicitly with or without parameter ‡ IT has two parts.Procedures Features ‡ It is a sub program in the PL/SQL block.

All Rights Reserved 71 .Creating Procedures ‡ Syntax CREATE OR REPLACE PROCEDURE <PROCEDURE_NAME> (<PARAMETER> [MODE] <DATA TYPE>.) IS/AS [LOCAL VARIABLE DECLARATION] BEGIN PL/SQL EXECUTABLE STATEMENT [EXCEPTION] [EXCEPTION HANDLERS] END [PROGRAM UNIT NAME]. Cognizant Academy. ©Copyright 2004.

nextval.credits) values (student_sequence.i_first_name. commit.last_name.i_major.last_name%type. student.Creating Procedures ‡ Example CREATE OR REPLACE PROCEDURE AddStudent ( i_first_name i_last_name i_major BEGIN INSERT INTO student (id. All Rights Reserved 72 .0).major. Cognizant Academy.major%type) AS ©Copyright 2004. END AddStudent.first_name.i_last_name . student. student.first_name%type.

program ± Can be changed inside ‡ INOUT ± Takes the value inside a sub.IN.program ‡ OUT ± Takes the value out of the sub. Cognizant Academy.Passing Parameters Formal parameters can have three modes .program ©Copyright 2004. All Rights Reserved 73 . OUT or IN OUT ‡ IN ± Default mode ± Takes the value inside the program ± Cannot be changed inside the sub.program and brings it out of the sub.

All Rights Reserved 74 . Cognizant Academy.Passing Parameters Procedure without parameter CREATE OR REPLACE PROCEDURE procedure_name AS /* Declarative section is here */ BEGIN /* Executable section is here */ Exception /* Exception section is here */ END [procedure_name] ©Copyright 2004.

All Rights Reserved 75 . ©Copyright 2004. END IF.Passing Parameters Example of Procedure with Parameter CREATE OR REPLACE PROCEDURE CALC_BONUS ( EMP_ID IN INTEGER. IF MJOB = µMANAGER¶ THEN BONUS := 0. BONUS OUT NUMBER) IS MJOB EMP. Cognizant Academy. END CALC_BONUS.10 INTO BONUS FROM EMP WHERE EMPNO = EMP_ID. BEGIN SELECT SAL*0.JOB%TYPE.

All Rights Reserved 76 . CALC_BONUS(ECODE.Passing Parameters Executing The Procedure DECLARE BON NUMBER. DBMS_OUTPUT. Cognizant Academy. / ©Copyright 2004. END. BEGIN ECODE := &EMPLOYEE_NO. BON).PUT_LINE(µThe Bonus for the employee¶ || ECODE || µ is¶ || BON). ECODE NUMBER.

Passing Parameters Example of Procedure with INOUT Parameter CREATE OR REPLACE PROCEDURE FORMAT_PHONE_NO ( V_PHONE IN OUT VARCHAR2) IS BEGIN V_PHONE := µ(µ || SUBSTR(V_PHONE.4.1. All Rights Reserved 77 .3) || µ)¶ || SUBSTR (V_PHONE.3) || µ-¶ || SUBSTR(V_PHONE. Cognizant Academy. / ©Copyright 2004. END FORMAT_PHONE_NO.7).

Creating Functions ‡ A function is a sub-program that is used to calculate value ‡ Must RETURN a single value at a time ‡ Can be used in a SELECT statement ‡ Syntax CREATE OR REPLACE FUNCTION< FUNCTION NAME> [ARGUMENT] RETURN DATATYPE IS[<LOCAL DECLARATION>] BEGIN EXECUTABLE STATEMENTS [EXCEPTION] [EXCEPTION HANDLERS] END [FUNCTION_NAME]. ©Copyright 2004. All Rights Reserved 78 . Cognizant Academy.

ELSIF stud_code = 'P' THEN RETURN 'Parmanent'. END.Creating Functions ‡ Example FUNCTION student_type (stud_code IN VARCHAR2) RETURN VARCHAR2 IS BEGIN IF stud_code = µT' THEN RETURN µTemp'. ©Copyright 2004. All Rights Reserved 79 . END IF. Cognizant Academy.

Packages ‡ A collection of Functions. PL/SQL types. Cognizant Academy. exception. Global variables and cursors stored in server in compiled form ‡ Consists of 2 parts ± Package Specification : This acts as an interface to the user applications. variables. This part declares the . constants. This part is created using CREATE PACKAGE command ± Package Body : It implements the specifications by defining the cursors and sub-programs. All Rights Reserved 80 . cursor & sub-programs(Functions and procedures). Procedures. This part is created using CREATE PACKAGE BODY command ©Copyright 2004.

Cognizant Academy. All Rights Reserved 81 .Packages ‡ Oracle stores package specification and body separately in the data dictionary ‡ A package specification can exists without a package body but not vice versa ©Copyright 2004.

Packages ‡ An element of a package. whether it is a variable or a module. but does not appear in the specification ± A private element cannot be referenced outside of the package ± It can only be referenced by other elements within the package ©Copyright 2004. can either be ‡ Public ± When defined in the specification ± A public element can be referenced from other programs and PL/SQL blocks ‡ Private ± When defined only in the body of the package. All Rights Reserved 82 . Cognizant Academy.

then all other sub-programs are also loaded into the memory.) operator ‡ When one sub-program is called. Only the procedures and functions from within the package can be called with reference to the package using the dot(.Packages ‡ The sub-programs that are present inside a package cannot exist separately as database objects ‡ A package cannot be called by itself. hence the subsequent call for any other modules becomes fast ©Copyright 2004. Cognizant Academy. All Rights Reserved 83 .

dbms_output. PROCEDURE P2 AS BEGIN I := I .put_line(I). ©Copyright 2004. Cognizant Academy. All Rights Reserved 84 .put_line(I). PROCEDURE P2. CREATE PACKAGE BODY PK1 AS I Integer :=0.50. END P1. PROCEDURE P1 AS BEGIN I := I + 100. dbms_output.Packages Example CREATE PACKAGE PK1 AS PROCEDURE P1. END P2. END PK1. END PK1.

Procedures. All Rights Reserved 85 . Cognizant Academy. which can perform a specific task when invoked explicitly with or without parameter ‡ PL/SQL functions returns scalar values while procedures nothing ‡ PL/SQL procedure/function argument can be of input (indicating the argument is read-only). output (indicating the argument is writeonly) or both (both readable and writable) ©Copyright 2004. Functions and Packages : Summary ‡ PL/SQL procedures/functions are compiled program database objects.

Cognizant Academy. exceptions. and so implements the specification ©Copyright 2004. It consists of two parts : specification and body ‡ The specification is the interface to your applications. All Rights Reserved 86 . variables. sub-programs etc.Procedures. it declares the types. constants. The body fully defines cursors and subprograms. and subprograms available for use. cursors. Functions and Packages : Summary ‡ A package is a compiled database objects logically groups PL/SQL types.

Installment amount will be 1/10th of monthly salary) ©Copyright 2004. (Max loan amount will be his current salary * total number of years of service. Loan will be paid in equal monthly installment. Cognizant Academy. All Rights Reserved 87 . ‡ Create a procedure which will accept the LOAN amount and EMPNO as input and display the installment amount and number of installments to be paid. and will show the reflection on the total salary.: Quiz ‡ Create a procedure which will accept a percentage and JOB. Calculate the total salary before the increment for the particular JOB and show the difference.

©Copyright 2004. Cognizant Academy. All Rights Reserved 88 .

Cognizant Academy. Appreciate Database Triggers 2. Components of Triggers 3.5. Order of Trigger Firing ©Copyright 2004. Triggers are used to overcome the limitations of constraints and to supplement the declarative referential integrity while implementing complex business rules or to audit changes to data Objective: After completing this module. you will be able to. Types of Triggers 4.0 Triggers : Overview Introduction: A database trigger is a stored program unit associated with a database table. All Rights Reserved 89 . Create Triggers 5. 1 .

Database Triggers ‡ These are stored procedures that gets implicitly executed when some database-related event occurs ‡ Can be applied on any Table/View ‡ Can be applied before the instruction is executed as well as after the execution ‡ Can work for any DML statements like INSERT. Cognizant Academy. All Rights Reserved 90 . UPDATE and DELETE but not for SELECT ‡ Can be used to overcome the limitation of CHECK constraints ©Copyright 2004.

©Copyright 2004. All Rights Reserved 91 . Cognizant Academy.Database Triggers ‡ Triggers should be designed to ± To perform operations that are related specific operations ± To perform operations that are global in nature ‡ Triggers Should not be designed ± To replace the functionality that already exists in the Oracle Server ‡ Syntax CREATE OR REPLACE TRIGGER <TRIGGER_NAME> [BEFORE/AFTER] [INSERT/UPDATE/DELETE] ON <TABLE_NAME> [ FOR EACH ROW [WHEN triggering_condition]] trigger_body.

UPDATE or DELETE ‡ Trigger Type ± The type of trigger can be Statement or Row ‡ Trigger Body ± This section specifies the action need to be performed by the trigger i.Components of Triggers ‡ Trigger Timing ± IT means when a trigger should fire. The possible trigger timing are BEFORE. it is the PL/SQL block that gets executed ©Copyright 2004. AFTER ‡ Trigger Event ± The trigger event can be INSERT. All Rights Reserved 92 . Cognizant Academy.e.

All Rights Reserved 93 . Cognizant Academy.Types of Triggers ‡ Row Level ± The action specified with the row level trigger will be executed for each affected row by the instruction for which the trigger is invoked ± These triggers will fire for every INSERT/UPDATE/DELETE on the table depending on the number of rows affected by by the triggering event ± Should specify the keyword FOR EACH ROW ‡ Statement Level ± They get fired in the table level once for each trigger event ± These triggers will fire for every INSERT/UPDATE/DELETE on the table irrespective of the number of rows affected by by the triggering event ± To define a statement level trigger omit the FOR EACH ROW keyword in the trigger specification ©Copyright 2004.

END major_stats.Creating Triggers Example of Statement Level Trigger CREATE OR REPLACE TRIGGER major_stats BEFORE INSERT ON major_stats BEGIN INSERT INTO temp_table (char_col) VALUES (µTrigger fired¶). Cognizant Academy. All Rights Reserved 94 . / ©Copyright 2004.

All Rights Reserved 95 . Cognizant Academy.Creating Triggers ‡ Row Level Trigger ‡ Row level trigger use :old and :new qualifiers to access value of a column before or after the change of data caused by a DML operation ‡ Old and New qualifiers can only be used in Row level triggers ‡ The table illustrates the old and new value of a database table column before and after DML operation DML Operations Value Before Change Value After Change INSERT UPDATE DELETE NULL Value before update Value before update Value that is inserted Value before update NULL ©Copyright 2004.

Cognizant Academy.num_col := old.char_col := :old.char_col. v_TempRec.Creating Triggers ‡ Example of Row Level Trigger CREATE OR REPLACE TRIGGER TempDelete BEFORE DELETE ON temp_table FOR EACH ROW DECLARE v_TempRec temp_table%ROWTYPE. All Rights Reserved 96 . BEGIN v_TempRec. ©Copyright 2004.num_col. END TempDelete.

if present ‡ For each row affected by the statement. ‡ Execute the after statement-level trigger. if present. All Rights Reserved 97 .Order of Trigger Firing ‡ Execute the BEFORE statement level trigger. ± Execute the statement itself. ± Execute the BEFORE row-level trigger. if present ©Copyright 2004. Cognizant Academy. if present. ± Execute the AFTER row-level trigger.

‡ The action specified with the row level trigger will be executed for each affected row by the instruction for which the trigger is invoked ‡ The statement level triggers will fire for every INSERT/UPDATE/DELETE on the table irrespective of the number of rows affected by by the triggering event ©Copyright 2004. All Rights Reserved 98 . UPDATE and DELETE but not for SELECT ‡ Triggers can be row level and statement level. Cognizant Academy.Triggers : Summary ‡ Triggers are stored procedures that gets implicitly executed when some database-related event occurs ‡ Can work for any DML statements like INSERT.

In case of record updation the NOE of one department should be reduced and another should be incremented.: Quiz ‡ Write a trigger on the EMP table. so that after each insertion of new record. Cognizant Academy. Add a column NOE to the dept table. the NOE column of the dept table gets updated. ©Copyright 2004. All Rights Reserved 99 . or updation of old one. which will record the number of rows for each department.

All Rights Reserved 100 . Cognizant Academy.©Copyright 2004.

Learn Multi-level collection ©Copyright 2004. you will be able to. Define and Declare Collection 4.6. Use Collection Methods 5.0 PL/SQL Collections : Overview Introduction: Oracle implements collection using Tables and Varrays Objective: After completing this module. All Rights Reserved 101 . Types of Collection 3. 1. Cognizant Academy. Understand Collections 2.

all of the same type ‡ It is a general concept that encompasses list. All Rights Reserved 102 . arrays and other familiar datatypes ‡ Each element has a unique subscript that determines its position in the collection ‡ Collections work like the arrays found in most third-generation programming language ©Copyright 2004. Cognizant Academy.Collection ‡ A collection is a ordered group of elements.

All Rights Reserved 103 . Cognizant Academy.Types of Collection ‡ PL/SQL has two collection types: ‡ Tables ‡ Varrays ‡ Tables comes in two flavors ± Index by tables(formerly called PL/SQL tables) ± Nested Tables ©Copyright 2004.

Types of Collection
Index-by Tables
‡ Also known as associative arrays, lets you look up elements using arbitrary numbers and strings for subscript values. ‡ They are similar to one-dimensional arrays and are referenced like arrays of records. Since Index-By tables can be passed as parameters, they can be used to move columns of data into and out of database tables or between client-side applications and stored subprograms

©Copyright 2004, Cognizant Academy, All Rights Reserved

104

Types of Collection
Nested Tables
‡ Nested tables hold an arbitrary number of elements. ‡ They use sequential numbers as subscripts. ‡ Within the database, nested tables can be considered one-column database tables ‡ Oracle stores the rows of a nested table in no particular order. ‡ when the nested table is retrieve into a PL/SQL variable, the rows are given consecutive subscripts starting at 1. That gives array-like access to individual rows.
©Copyright 2004, Cognizant Academy, All Rights Reserved 105

Types of Collections
Difference between Array and Nested Tables
‡ First, arrays have a fixed upper bound, but nested tables are unbounded. So, the size of a nested table can increase dynamically ‡ Second, arrays must be dense (have consecutive subscripts). So, individual elements cannot be deleted from an array. Initially, nested tables are dense, but they can be sparse (have nonconsecutive subscripts).

©Copyright 2004, Cognizant Academy, All Rights Reserved

106

All Rights Reserved 107 . Cognizant Academy. That might leave gaps in the index.Types of Collections ‡ Elements from a nested table can be deleted using the built-in procedure DELETE. but the built-in function NEXT allows iteration over any series of subscripts ©Copyright 2004.

Cognizant Academy.Types of Collections Varrays ‡ Items of type VARRAY are called varrays ‡ Allow to associate a single identifier with an entire collection ‡ Manipulate the collection as a whole and reference individual elements easily ‡ To reference an element. ©Copyright 2004. All Rights Reserved 108 . Grade (3) references the third element in varray Grades. use standard subscripting syntax ‡ Example.

All Rights Reserved 109 . You mustSpecify the size. STRING. Element_type is any PL/SQL datatype. or LONG. Key_type can be numeric.) ©Copyright 2004. INDEX BY key_type. It can also be VARCHAR2 or one of its subtypes VARCHAR. (Varchar2 (1000). either BINARY_INTEGER or PLS_INTEGER. ± ± ± ± Type_name is a type specifier used later to declare collections. Cognizant Academy.Declaring and Defining Collection ‡ Define a collection type and declare variables of that type ‡ Syntax for Index-by tables: TYPE type_name IS TABLE OF element_type [NOT NULL] INDEX BY [BINARY_INTEGER | PLS_INTEGER | VARCHAR2(size_limit)].

©Copyright 2004. All Rights Reserved 110 . ± type_name is a type specifier used later to declare collections ± element_type is any PL/SQL datatype. must specify its maximum size.Declaring and Defining Collection ‡ Syntax for Nested tables: TYPE type_name IS TABLE OF element_type [NOT NULL]. ± type_name and element_type are the same as for nested tables.size_limit is a positive integer literal representing the maximum number of elements in the array ‡ When defining a VARRAY type. Cognizant Academy. of a type that stores up to 366 dates: DECLARETYPE Calendar IS VARRAY (366) OF DATE. ‡ Syntax for Varrays: TYPE type_name IS {VARRAY | VARYING ARRAY} (size_limit) OF element_type [NOT NULL]. ‡ Example.

©Copyright 2004. empid_tab typ_number.by Tables ± DECLARE TYPE EmpTabTyp IS TABLE OF emp%ROWTYPE /* Create a type */ INDEX BY BINARY_INTEGER. /* Declaration of variable of collection type */ ± TYPE typ_number IS TABLE OF NUMBER INDEX BY BINARY_INTEGER. All Rights Reserved 111 .Declaring and Defining Collection ‡ Example of Index. Cognizant Academy. */ SELECT * INTO emp_tab(7468) FROM emp WHERE empno = 7468. emp_tab EmpTabTyp. /* Declaration of variable of collection type */ BEGIN /* Retrieve employee record.

empid_tab. END. All Rights Reserved 112 .last > 0 THEN FORALL I in 1. END LOOP ©Copyright 2004.. Cognizant Academy.put_line(µEmpid: µ||empid_tab(i)) END IF.last LOOP Dbms_output. IF empid_tab.Declaring and Defining Collection SELECT EMPID BULK COLLECT INTO empid_tab FROM EMP.

declare nested table as attribute / ©Copyright 2004. courses CourseList) -. status CHAR(2).define type / CREATE TYPE Student AS OBJECT ( -.Declaring and Defining Collection ‡ Example of Nested Tables: CREATE TYPE CourseList AS TABLE OF VARCHAR2(10) -. name VARCHAR2(25). Cognizant Academy. address VARCHAR2(35).create object id_num INTEGER(4). All Rights Reserved 113 .

PHONENUMBER TYP_NUMBER ) NESTED TABLE PHONENUMBER STORE AS PHONENUMBER_TAB / ©Copyright 2004. All Rights Reserved 114 . Cognizant Academy.Declaring and Defining Collection ‡ Example of Nested Tables: CREATE OR REPLACE TYPE TYP_NUMBER AS TABLE OF NUMBER / CREATE TABLE TMP (EMPID NUMBER. EMPNAME VARCHAR2 (100).

/ CREATE TABLE department ( -. budget NUMBER(11. All Rights Reserved 115 . name VARCHAR2(15).Declaring and Defining Collection ‡ Example of Varrays CREATE TYPE ProjectList AS VARRAY(50) OF VARCHAR2(16). Cognizant Academy.Each department can have up to 50 projects. projects ProjectList) / ©Copyright 2004. -.create database table dept_id NUMBER(2).2).

method_name[(parameters)] ‡ The following collection methods help generalize code. Cognizant Academy.Using Collection Methods ‡ A collection method is a built-in function or procedure that operates on collection ‡ Is called using dot notation ‡ Syntax: ± collection_name.And make your application easier to maintain ©Copyright 2004. All Rights Reserved 116 . make collections easier to use.

©Copyright 2004. Cognizant Academy. or NULL for nested tables. ‡ LIMIT . ‡ COUNT . so that the records can be sized to fit into free memory for faster processing. This is specifically useful to determine batch size when dealing with large number of records.Returns the number of elements in the collection.Returns TRUE if the specified element exists.Using Collection Methods ‡ EXISTS(n) .Returns the maximum number of elements for a VARRAY. All Rights Reserved 117 .

©Copyright 2004.Returns the index of the element prior to the specified element ‡ NEXT(n) .Returns the index of the next element after the specified element. ‡ EXTEND(n) .Returns the index of the first element in the collection.Appends a single null element to the collection. ‡ EXTEND .Using Collection Methods ‡ FIRST . ‡ LAST . ‡ PRIOR(n) . Cognizant Academy. All Rights Reserved 118 .Returns the index of the last element in the collection.Appends n null elements to the collection.

Cognizant Academy.Removes all elements from n1 to n2 from the collection ©Copyright 2004.Removes all elements from the collection.Appends n1 copies of the n2th element to the collection ‡ TRIM . ‡ DELETE(n) . n2) . ‡ DELETE(n1.Removes a single element from the end of the collection.Using Collection Methods ‡ EXTEND(n1.Removes element n from the collection. All Rights Reserved 119 .Removes n elements from the end of the collection. ‡ DELETE . ‡ TRIM(n) .n2) .

-. type nt1 is varray(10) of t1. -. t1(2.multilevel access i := nva(2)(3).3. t1(55.6.multilevel va t1 := t1(2.5).Multi-level Collection ‡ ‡ ‡ It¶s a collection within collections Examples are Nested table of varrays.i will get value 73 dbms_output. Cognizant Academy. va1 t1.4). All Rights Reserved 120 . Varrays of varrays etc Multilevel VARRAY Example declare type t1 is varray(10) of integer. begin -.73). -.initialize multilevel varray nva nt1 := nt1(va.put_line(i). i integer. ©Copyright 2004.

Cognizant Academy. all of the same type ‡ Each element has a unique subscript that determines its position in the collection ‡ PL/SQL has two collection types: Tables. All Rights Reserved 121 .PL/SQL Collection : Summary ‡ A collection is a ordered group of elements. Varrays ‡ Tables comes in two flavors Index by tables (formerly called PL/SQL tables) and Nested Tables ©Copyright 2004.

create object id_num INTEGER(4). DELETE(6.7) delete element 7Then courses. DELETE(2). CREATE TYPE CourseList AS TABLE OF VARCHAR2(10) -. address VARCHAR2(35). DELETE(7.declare nested table as attribute / If courses .define type / CREATE TYPE Student AS OBJECT ( -. courses CourseList) -. name VARCHAR2(25).3) delete which element? ©Copyright 2004. All Rights Reserved 122 . status CHAR(2).: Quiz ‡ Study the following code. Cognizant Academy. deletes element 2 and courses .

Cognizant Academy.©Copyright 2004. All Rights Reserved 123 .

Use Dynamic SQL 3. 1. you will be able to. Understand Dynamic SQL 2.0 Dynamic SQL : Overview Introduction: Dynamic SQL is an advanced programming technique that adds flexibility and functionality to applications Objective: After completing this module.7. All Rights Reserved 124 . Understand BULK COLLECT 7. Execute Dynamic SQL 4. Cognizant Academy. Appreciate the difference between Soft Parse and Hard Parse ©Copyright 2004. Understand FOR ALL 6. Understand BULK Operations 5.

All Rights Reserved 125 . The full text of static SQL statements are known at Compilation time that is not there in case of Dynamic sql ©Copyright 2004. a clear definition of static SQL may provide a good starting point for understanding dynamic SQL ‡ Static SQL statements do not change from execution to execution. Cognizant Academy.Dynamic SQL ‡ Dynamic SQL enables to write programs that reference SQL statements whose full text is not known until runtime ‡ Before discussing dynamic SQL in detail.

data definition language (DDL) statements such as CREATE.e. Cognizant Academy. data control Statement such as GRANT and session control statement such as ALTER SESSION ‡ Dynamic SQL should be used in cases where static SQL does not support ‡ The operation you want to perform or in cases you do not know the exact ‡ SQL statements that must be executed by a PL/SQL procedure i. at Runtime ©Copyright 2004. All Rights Reserved 126 .Use of Dynamic SQL ‡ Dynamic SQL lets execute SQL statements that are not supported in static SQL Programs.

| record}] ©Copyright 2004.. All Rights Reserved 127 . define_variable]..Execution of Dynamic SQL Using the EXECUTE IMMEDIATE Statement ‡ The EXECUTE IMMEDIATE statement prepares (parses) and immediately executes a dynamic SQL statement or an anonymous PL/SQL block ‡ Syntax EXECUTE IMMEDIATE dynamic_string [INTO {define_variable[. Cognizant Academy.

©Copyright 2004... [IN | OUT | IN OUT] bind_argument]. Cognizant Academy.Execution of Dynamic SQL [USING [IN | OUT | IN OUT] bind_argument [. ± define_variable is a variable that stores a SELECTed column value. ± where dynamic_string is a string expression that represents a SQL statement or PL/SQL block.]. All Rights Reserved 128 . ± bind_argument is an expression whose value is passed to the dynamic SQL statement or PL/SQL block. record is a user-defined or %ROWTYPE record that stores a SELECTed row.

For each column value returned by the query. Dynamic SQL supports all the SQL datatypes. instances of an object type. ± So. and string literals are allowed in the USING clause. every placeholder must be associated with a bind argument in the USING clause. any bind arguments in the USING clause replace corresponding placeholders in the SQL statement or PL/SQL block. To pass nulls to the dynamic string. there must be a corresponding. All Rights Reserved 129 . If no parameter mode is specified. useful only for single-row queries. FALSE. So. At run time. for example.Execution of Dynamic SQL ± The INTO clause. define variables and bind arguments can be collections. Numeric. type-compatible variable or field in the INTO clause ± Every bind argument must be put in the USING clause. specifies the variables or Record into which column values are fetched. character. a workaround must be used. and REFs ©Copyright 2004. NULL) are not. LOBs. but Boolean literals (TRUE. Cognizant Academy. it defaults to IN.

Cognizant Academy.Execution of Dynamic SQL ‡ Example using EXECUTE IMMEDIATE ‡ Example 1 DECLARE sql_stmt VARCHAR2(100). BEGIN sql_stmt := ¶INSERT INTO dept VALUES (:1. EXECUTE IMMEDIATE sql_stmt USING my_deptno. my_loc VARCHAR2(15) := ¶DALLAS¶. All Rights Reserved 130 . ©Copyright 2004. my_dname. sql_stmt := ¶SELECT * FROM emp WHERE empno = :id¶. plsql_block VARCHAR2(200). :3)¶. :2. emp_rec emp%ROWTYPE. my_dname VARCHAR2(15) := ¶PERSONNEL¶. my_loc. my_deptno NUMBER(2) := 50.

raise_salary(:id. sql_stmt := ¶ALTER SESSION SET SQL_TRACE TRUE¶. END. plsql_block := ¶BEGIN emp_stuff. amt NUMBER)¶. END. :amt). EXECUTE IMMEDIATE ¶DELETE FROM dept WHERE deptno = :n¶ USING my_deptno. All Rights Reserved 131 . ©Copyright 2004. EXECUTE IMMEDIATE plsql_block USING 7788.¶. EXECUTE IMMEDIATE ¶CREATE TABLE bonus (id NUMBER. EXECUTE IMMEDIATE sql_stmt.Execution of Dynamic SQL EXECUTE IMMEDIATE sql_stmt INTO emp_rec USING 7788. 500. Cognizant Academy.

deptname VARCHAR2. location.Execution of Dynamic SQL ‡ Example 2 CREATE PROCEDURE insert_into_table ( table_name VARCHAR2. ©Copyright 2004. deptnumber NUMBER. :dname. EXECUTE IMMEDIATE stmt_str USING deptnumber. END. deptname. BEGIN stmt_str := ¶INSERT INTO ¶ || table_name || ¶ values (:deptno. All Rights Reserved 132 . Cognizant Academy. location VARCHAR2) IS stmt_str VARCHAR2(200). :loc)¶.

:dname. Deptnumber NUMBER.Execution of Dynamic SQL ‡ Example using the DBMS SQL package CREATE PROCEDURE insert_into_table ( Table_name VARCHAR2. :loc)'. -----Open cursor cur_hdl := dbms_sql. Cognizant Academy.open_cursor. All Rights Reserved 133 . Rows_processed BINARY_INTEGER. Deptname VARCHAR2. ©Copyright 2004. BEGIN Stmt_str := 'INSERT INTO ' || Table_name || ' VALUES (:deptno. Stmt_str VARCHAR2(200). Location VARCHAR2) IS Cur_hdl INTEGER.

':deptno'.Close cursor dbms_sql.bind_variable (cur_hdl. dbms_sql. stmt_str.Execute cursor rows_processed := dbms_sql.close_cursor(cur_hdl).dbms_sql.Supply binds dbms_sql. ----.execute(cur_hdl).bind_variable (cur_hdl. deptname). dbms_sql.Parse cursor dbms_sql. ---.Execution of Dynamic SQL ---. ':loc'. deptnumber).bind_variable (cur_hdl. ---. location). ':dname'. All Rights Reserved 134 .parse(cur_hdl. Cognizant Academy. ©Copyright 2004. END.native).

but all SQL statement are passed to SQL layer for execution. All Rights Reserved 135 . the procedural portions are executed by the PL/SQL engine. Cognizant Academy. then data is passed back to the procedural engine ©Copyright 2004. but this tight integration does not mean that there isn¶t any overhead associated with executing SQL statements from PL/SQL ‡ When a PL/SQL program executes.Bulk Operations ‡ PL/SQL is very tightly integrated with the Oracle database SQL engine.

The more switches occur the more performance degrades. Cognizant Academy. All Rights Reserved 136 . Two new enhancements ‡ BULK COLLECT and the FORALL statements allows to bulk together all of the context switches into a single switch and pass that to the SQL engine ©Copyright 2004.Bulk Operations ‡ The transfer of data back and forth from PL/SQL to SQL and back again is called context switching.

©Copyright 2004. Cognizant Academy. All Rights Reserved 137 .FOR ALL ‡ A variation on the classic FOR LOOP that bundles together multiple DML statements based on a collection ‡ Bulk DML using the FORALL statement will also take advantage of turning multiple context switches into a single context switch. ‡ The FORALL statement must follow these simple rules: ‡ The body of the FORALL statement must contain a single DML operation.

you may not reference it outside of that statement ‡ Do not declare an INTEGER variable for index_row. All Rights Reserved 138 .FOR ALL ‡ The DML must reference collection elements. Cognizant Academy. The scope of the index_row variable is the FORALL statement only. ©Copyright 2004. indexed by the index_row variable in the FORALL statement. It is declared implicitly by the PL/SQL engine ‡ The lower and upper bounds must specify a valid range of consecutive index numbers for the collection(s) referenced in the SQL statement.

FOR ALL ‡ Example PROCEDURE proc_bulk_collect IS CURSOR cur_emp IS SELECT emono FROM emp. FORALL i IN tab_emono. ©Copyright 2004. END LOOP. TYPE tt_empno IS TABLE OF emp.tab_emono.empno%TYPE INDEX BY BINARY_INTEGER.. All Rights Reserved 139 .FIRST. end.LAST LOOP DELETE FROM new_emp WHERE empno = tab_emono(i). BEGIN OPEN cur_emp. Cognizant Academy. tab_emono tt_empno. FETCH cur_emp INTO BULK COLLECT tab_emono. close cur_emp.

BULK COLLECT ‡ An enhancement to explicit and implicit cursor query operation that allows the transfer of multiple rows of data in one trip to the SQL engine PROCEDURE proc_bulk_collect IS CURSOR cur_emp IS SELECT emono.ename FROM emp.empno%TYPE INDEX BY BINARY_INTEGER. close cur_emp. Cognizant Academy.tab_ename. TYPE tt_empno IS TABLE OF emp. FETCH cur_emp INTO BULK COLLECT tab_emono. tab_emono tt_empno. TYPE tt_ename IS TABLE OF emp. All Rights Reserved 140 . BEGIN OPEN cur_emp. ©Copyright 2004. END.ename%TYPE INDEX BY BINARY_INTEGER. tab_ename tt_ename.

Hard parse can be avoid by using bind variable in subprogram ©Copyright 2004. which are parsed every time during the execution is called Hard parse. A shorter process to getting the query result ‡ Hard parse: statement. our system will function slowly and in some cases. If we have to Hard Parse a large percentage of our queries. Cognizant Academy. All Rights Reserved 141 . which are parsed and already in the shared pool. those statements for re-execution need not require parsing if it is found in the shared Pool.Difference between soft parse and hard parse ‡ Soft parse: Statement.

All Rights Reserved 142 .Dynamic SQL : Summary ‡ Dynamic SQL enables to write programs that reference SQL statements whose full text is not known until runtime ‡ Dynamic SQL lets execute SQL statements that are not supported in static SQL Programs ‡ The EXECUTE IMMEDIATE statement prepares (parses) and immediately executes a dynamic SQL statement or an anonymous PL/SQL block ‡ BULK COLLECT and the FORALL statements allows to bulk together all of the context switches into a single switch and pass that to the SQL engine ©Copyright 2004. Cognizant Academy.

DBMS_SQL.: Quiz ‡ The following are the two Dynamic SQL statements. 'CREATE TABLE X (Y DATE)'. End. / CREATE OR REPLACE PROCEDURE CREATE_TABLE2 AS cur integer. DBMS_SQL. What is the main difference between this two statements in the respect of execution. rc integer.OPEN_CURSOR.CLOSE_CURSOR(cur).PARSE(cur. / ©Copyright 2004. Cognizant Academy.NATIVE). Begin EXECUTE IMMEDIATE 'CREATE TABLE X(A DATE)'. All Rights Reserved 143 . rc := DBMS_SQL. DBMS_SQL.EXECUTE(cur). BEGIN cur := DBMS_SQL. END.

©Copyright 2004. Cognizant Academy. All Rights Reserved 144 .

Cognizant Academy.com ©Copyright 2004.Oracle 9i: Next Step The following items will provide more information on the subjects covered in this course: Resource Type Book Book PDF PDF URL White Paper Research article e-learning course Description Oracle 8i Complete Reference Oracle PL/SQL Programming by Steven Feuerstein and Bryn Llewellyn Reference Topic or Module http://otn.oracle. All Rights Reserved 145 .

Oracle 9i - Summary
‡ An Oracle server consists of an Oracle database and an Oracle server instance ‡ Oracle processes can be user process and server process ‡ Physical database structure includes data file, redo log file and control files ‡ All the data dictionary tables and views for a given database are stored in that database¶s SYSTEM tablespace ‡ SQL is an English-like, non-procedural language

©Copyright 2004, Cognizant Academy, All Rights Reserved

146

Oracle 9i - Summary
‡ SQL is used in creating, modifying and deleting database objects ‡ SQL *PLUS is an Oracle tool. It recognizes and submits SQL statements residing in the SQL buffer (memory area) for execution to the Oracle server ‡ PL/SQL extends SQL by adding constructs found in other procedural languages like conditional constructs, looping, variables data types, procedures, functions etc. ‡ A SQL cursor is a private Oracle SQL working area

©Copyright 2004, Cognizant Academy, All Rights Reserved

147

Oracle 9i - Summary
‡ The implicit cursor is used by Oracle server to test and parse the SQL statements. Explicit cursors are declared by the programmers ‡ PL/SQL traps and responds to errors using an architecture of EXCEPTION handler. Pre-defined exceptions are already defined in the STANDARD package ‡ PL/SQL procedures/functions are compiled program database objects, which can perform a specific task when invoked explicitly with or without parameter

©Copyright 2004, Cognizant Academy, All Rights Reserved

148

all of the same type ‡ Dynamic SQL enables to write programs that reference SQL statements whose full text is not known until runtime ©Copyright 2004. Cognizant Academy. sub-programs etc. It consists of two parts : specification and body ‡ Triggers are stored procedures that gets implicitly executed when some database-related event occurs ‡ A collection is a ordered group of elements.Oracle 9i . All Rights Reserved 149 .Summary ‡ A package is a compiled database objects logically groups PL/SQL types.

Congratulations! You have successfully completed Oracle 9i .

Sign up to vote on this title
UsefulNot useful