Oracle PL/SQL

CONTENTS
PL/SQL.......................................................................................................................................................... 3 INTRODUCTION TO PL/SQL...................................................................................................................... 4 Topics ..................................................................................................................................................... 4 New Features in PL/SQL........................................................................................................................ 5 PL/SQL Architecture .............................................................................................................................. 6 PL/SQL Block Structure ......................................................................................................................... 7 PL/SQL Data Types................................................................................................................................ 8 Declaring Variables and Constants...................................................................................................... 10 Conditional Control Statements ........................................................................................................... 12 Iterative Control Statements................................................................................................................. 12 Loop Labels .......................................................................................................................................... 13 Sequential Control: GOTO and NULL Statements............................................................................... 13 SQL Support in PL/SQL ....................................................................................................................... 15 User-Defined Records .......................................................................................................................... 16 Review Questions.................................................................................................................................. 18 CURSORS .................................................................................................................................................. 19 Topics ................................................................................................................................................... 19 What are Cursors? ............................................................................................................................... 20 Explicit Cursors.................................................................................................................................... 20 Cursor Attributes .................................................................................................................................. 22 Cursor FOR Loops ............................................................................................................................... 23 Passing Parameters to Cursors ............................................................................................................ 24 Using Cursor Variables........................................................................................................................ 25 Review Questions.................................................................................................................................. 29 Exercises............................................................................................................................................... 29 PROCESSING TRANSACTIONS IN PL/SQL ............................................................................................... 30 Topics ................................................................................................................................................... 30 Processing Transactions....................................................................................................................... 31 Overriding Default Locking.................................................................................................................. 33 ERROR HANDLING IN PL/SQL................................................................................................................ 35 Topics ................................................................................................................................................... 35 Exceptions ............................................................................................................................................ 36 Scope Rules........................................................................................................................................... 38 Using EXCEPTION_INIT..................................................................................................................... 39 Propagation of Exception..................................................................................................................... 39 Re-raising an Exception ....................................................................................................................... 40 SQLCODE and SQLERRM .................................................................................................................. 41 Review Questions.................................................................................................................................. 44 Exercises............................................................................................................................................... 44 SUBPROGRAMS AND PACKAGES .............................................................................................................. 46 Topics ................................................................................................................................................... 46 What are Subprograms?....................................................................................................................... 47 Procedures............................................................................................................................................ 48 Functions .............................................................................................................................................. 49 Declaring Subprograms ....................................................................................................................... 50 Stored Subprograms ............................................................................................................................. 51 Positional and Named Notation ........................................................................................................... 52 Overloading.......................................................................................................................................... 52 Recursion.............................................................................................................................................. 54 Packages............................................................................................................................................... 54 Package STANDARD ........................................................................................................................... 57

Jayashree

Page 1 of 69

Oracle PL/SQL

ORACLE Product-specific Packages ................................................................................................... 57 Advantages of Packages ....................................................................................................................... 58 Exercises............................................................................................................................................... 59 DATABASE TRIGGERS .............................................................................................................................. 60 Topics ................................................................................................................................................... 60 Introduction to Triggers ....................................................................................................................... 61 Creating a Database Trigger ............................................................................................................... 61 Triggers Examples................................................................................................................................ 63 INSTEAD OF Triggers ......................................................................................................................... 66 Trigger Execution................................................................................................................................. 68 Exercises............................................................................................................................................... 69

Jayashree

Page 2 of 69

Oracle PL/SQL

PL/SQL

• • • • • •

Introduction to PL/SQL Cursors Processing Transactions in PL/SQL Error Handling in PL/SQL : Exceptions Subprograms and Packages Database Triggers

Jayashree

Page 3 of 69

Oracle PL/SQL Introduction to PL/SQL Topics • • • • • • • • • • New Features in PL/SQL PL/SQL Architecture PL/SQL Block Structure PL/SQL Data Types Declaring Variables and Constants Conditional Control Statements Iterative Control Statements Loop Labels Sequential Control : GOTO and NULL Statements SQL Support in PL/SQL Jayashree Page 4 of 69 .

PL/SQL provides an interface for calling routines written in other languages. the standard data access language for object-relational databases. when the data structure is filled with values. You can create as many objects as you need. then calls the routine as if it were a PL/SQL subprogram. or control real-time devices and processes. Typically. analyze data. Object types. PL/SQL loads the library dynamically. information hiding. • Object Types • Object-oriented programming is based on the concept of interacting objects. Each object stores different real-world values. you have created an object. This allows you to create software components that are modular. At run time. solve scientific and engineering problems. external procedures are used to interface with embedded systems. New Features in PL/SQL • • • • External Procedures Object Types Collections LOB Types External Procedures • To support special-purpose processing and promote reuse of code. and called by you to do special-purpose processing. An object type encapsulates a data structure along with the functions and procedures needed to manipulate the data. exception handling. In. registered with PL/SQL. objects are instances of object types. This makes the strengths and capabilities of those languages available to you. reduce complexity by breaking down a large system into logical entities.Oracle PL/SQL PL/SQL is Oracle Corporation's procedural language extension to SQL. and so brings state-of-the-art programming to the Oracle Server and Toolset. and object orientation. and reusable. An external procedure is a third-generation-language routine stored in a dynamic link library (DLL). which map directly into classes defined in object-oriented languages such as C++. • • Jayashree Page 5 of 69 . At run time. you create an abstract template for some real-world object. PL/SQL. maintainable. When you define an object type using the CREATE TYPE statement (in SQL*Plus for example). PL/SQL offers modern software engineering features such as data encapsulation.

And. A collection is an ordered group of elements. you use the supplied package DBMS_LOB. collections can be passed as parameters. CLOB. all of the same type. • LOB Types • The LOB (large object) datatypes BFILE. PL/SQL can reside in two environments: the Oracle Server Oracle tools • • • • The PL/SQL Engine • The PL/SQL engine executes procedural statements but sends SQL statements to the SQL Statement Executor in the Oracle Server. Each element has a unique subscript that determines its position in the collection. piece-wise access to the data. So. can be attributes of an object type. So. that specify the location of large objects stored out-of-line or in an external file. Application development tools that lack a local PL/SQL engine must rely on Oracle to process PL/SQL blocks and subprograms. The engine can be installed in an Oracle Server or in an application development tool such as Oracle Forms or Oracle Reports. called locators. LOB types store values. Also. and NCLOB let you store blocks of unstructured data up to four gigabytes in size. • Jayashree Page 6 of 69 . random. BLOB. they allow efficient. you can use them to move columns of data into and out of database tables or between client-side applications and stored subprograms.Oracle PL/SQL Collections • The collection types TABLE and VARRAY allow you to declare nested tables and variable-size arrays (varrays for short). To manipulate LOBs. They can store instances of an object type and. Collections work like the arrays found in most third-generation programming languages. not an independent product. • PL/SQL Architecture • The PL/SQL runtime system is a technology. This technology acts as an engine that executes PL/SQL blocks and subprograms. conversely. PL/SQL operates on LOBs through the locators.

• PL/SQL is a block-structured language . The Oracle Server passes the blocks and subprograms to its local PL/SQL engine. You can nest sub-blocks in the executable and exception-handling parts of a PL/SQL block or subprogram but not in the declarative part. an Oracle Server can process PL/SQL blocks and subprograms as well as single SQL statements.Oracle PL/SQL • When it contains the PL/SQL engine. which can contain any number of nested sub-blocks. Only the executable part is required.the basic units (procedures. functions. • • • Jayashree Page 7 of 69 . A block (or sub-block) lets you group logically related declarations and statements. The declarations are local to the block and cease to exist when the block completes. PL/SQL Engine Non-SQL SQL Procedural Statement Executor PL/SQL Block PL/SQL Block SQL Statement Executor ORACLE Server PL/SQL Block Structure DECLARE < Declarations > BEGIN < Executable Statements > EXCEPTION < Exception Handlers > END. and anonymous blocks) that make up a PL/SQL program are logical blocks.

Scalar Types BINARY_INTEGER DEC DECIMAL DOUBLE-PRECISION INTEGER FLOAT INT INTEGER NATURAL NUMBER NUMERIC POSITIVE REAL SMALLINT SIGNTYPE Composite Types RECORD TABLE Reference Types REFCURSOR REF object_name LOB Types BFILE BLOB CLOB Subtypes A base type is the datatype from which a subtype is derived. A composite type has internal components that can be manipulated individually.Oracle PL/SQL PL/SQL Data Types Every constant and variable has a datatype. which specifies a storage format. A subtype associates a base type with a constraint and so defines a subset of values. CHAR CHARACTER LONG LONG RAW RAW ROWID STRING VARCHAR2 DATE BOOLEAN Jayashree Page 8 of 69 . constraints. and valid range of values. called locators. called pointers. A scalar type has no internal components. A LOB type holds values. that designate other program items. PL/SQL provides a variety of predefined datatypes. that specify the location of large objects (graphic images for example) stored out-of-line. A reference type holds values.

-.illegal. For example: DECLARE SUBTYPE Accumulator IS NUMBER(7. -.maximum size of Word is 15 Jayashree Page 9 of 69 .based on TABLE type TYPE TimeRec IS RECORD (minutes INTEGER. or package using the syntax SUBTYPE subtype_name IS base_type.-. SUBTYPE Word IS temp%TYPE. SUBTYPE EmpRoster IS NameList. -.illegal You can use a simple workaround to define size-constrained subtypes indirectly: DECLARE temp VARCHAR2(15).based on NATURAL subtype TYPE NameList IS TABLE OF VARCHAR2(10). SUBTYPE Delimiter IS CHAR(1). subprogram. hours INTEGER).2). Examples: DECLARE SUBTYPE EmpDate IS DATE. SUBTYPE Word IS VARCHAR2(15). -.based on DATE type SUBTYPE Counter IS NATURAL.Oracle PL/SQL BINARY_INTEGER NATURAL POSITIVE SIGNTYPE NUMBER DEC DECIMAL DEC DOUBLE PRECISION INTEGER INT NUMERIC REAL SMALLINT CHAR CHARACTER VARCHAR2 STRING VARCHAR User-Defined Subtypes You can define your own subtypes in the declarative part of any PL/SQL block. -.illegal. -. -.based on column type CURSOR c1 IS SELECT * FROM dept. you cannot specify a constraint on the base type. SUBTYPE Time IS TimeRec.based on RECORD type SUBTYPE ID_Num IS emp.--based on cursor rowtype However. -.empno%TYPE. SUBTYPE DeptFile IS c1%ROWTYPE.

• • • • • • • Jayashree Page 10 of 69 . employees Counter. Forward references are not allowed. declarations can impose the NOT NULL constraint. Examples: blood_type CHAR DEFAULT 'O'. including other declarative statements. and NUMBER. such as BOOLEAN and BINARY_INTEGER. Constants are declared by specifying the key word CONSTANT before the datatype. Example: credit_limit CONSTANT REAL := 5000. You can use the keyword DEFAULT instead of the assignment operator to initialize variables. rows Counter.00.Oracle PL/SQL Using Subtypes Once you define a subtype. you must declare a variable or constant before referencing it in other statements. you can declare items of that type.2). The NOT NULL constraint must be followed by an initialization clause. Variables can have any SQL data type. as the following example shows: acct_id INTEGER(4) NOT NULL := 9999. So. Besides assigning an initial value. DECLARE SUBTYPE Accumulator IS NUMBER. DATE. Examples: emp_no NUMBER(4). and then use them in SQL and procedural statements anywhere an expression can be used. Declaring Variables and Constants • PL/SQL allows you to declare variables and constants. Initial values can also be assigned to a variable at the time of declaration. total Accumulator(7. such as CHAR. or any PL/SQL data type. Examples: DECLARE SUBTYPE Counter IS NATURAL. in_stock BOOLEAN. Example: deptno NUMBER(4) := 10. valid BOOLEAN DEFAULT FALSE.

you need not know the exact data type of dname. • The %TYPE attribute is particularly useful when declaring variables that refer to database columns.dept.deptno • • • Jayashree Page 11 of 69 . Columns in a row and corresponding fields in a record have the same names and data types. Using %ROWTYPE Attribute • The %ROWTYPE attribute provides a record type that represents a row in a table (or view). the data type of my_dname changes accordingly at run time. Second. • Using %TYPE to declare my_dname has two advantages.Oracle PL/SQL Using %TYPE Attribute • The %TYPE attribute provides the data type of a variable or database column.2). you might reference the deptno field as emp_rec. debit credit%TYPE.00. Example : my_dname scott. you use dot notation. minimum_balance balance%TYPE := 10.2). if the database definition of dname changes.dname%TYPE. For example. balance NUMBER(7. The record can store an entire row of data selected from the table Example : emp_rec emp%ROWTYPE. First. Examples : credit REAL(7. To reference a field.

Iterative Control Statements LOOP sequence_of_statements. END IF.. ELSIF condition2 THEN sequence_of_statements2. Jayashree Page 12 of 69 . ELSE sequence_of_statements3.higher_bound LOOP sequence_of_statements. EXIT WHEN condition. END LOOP. END LOOP. WHILE condition LOOP sequence_of_statements. IF condition1 THEN sequence_of_statements1. EXIT. IF condition THEN sequence_of_statements1. FOR counter IN [REVERSE] lower_bound. END LOOP. ELSE sequence_of_statements2.Oracle PL/SQL Conditional Control Statements IF condition THEN sequence_of_statements. END IF. END IF.

-. .. but any enclosing loop. as the following example shows: <<my_loop>> LOOP . The label must be unique within its scope and must precede an executable statement or a PL/SQL block.. loops can be labeled.exit both loops Sequential Control: GOTO and NULL Statements • • The GOTO statement branches to a label unconditionally. END LOOP.. you can complete not only the current loop.. END LOOP.. as follows: <<outer>> LOOP .... use the label in an EXIT statement.. END LOOP outer. • Optionally. Then.Oracle PL/SQL Loop Labels • Like PL/SQL blocks. END LOOP my_loop. as follows: <<label_name>> LOOP sequence_of_statements. • With either form of EXIT statement. must appear at the beginning of the LOOP statement. EXIT outer WHEN . an undeclared identifier enclosed by double angle brackets. Jayashree Page 13 of 69 . the label name can also appear at the end of the LOOP statement.. Simply label the enclosing loop that you want to complete. LOOP . The label.

.50 LOOP IF done THEN GOTO end_loop.branch to enclosing block END. GOTO get_name. BEGIN . .Oracle PL/SQL GOTO Statement : Examples • BEGIN . LOOP statement. END.. -. <<get_name>> SELECT ename INTO my_ename FROM emp WHERE .. -.. GOTO insert_row. A GOTO statement cannot branch from an enclosing block into a sub-block Jayashree Page 14 of 69 .. • DECLARE done BEGIN BOOLEAN.. a GOTO statement cannot branch from one IF statement clause to another. <<insert_row>> INSERT INTO emp VALUES .. BEGIN ......... <<end_loop>> NULL.. • DECLARE my_ename CHAR(10). END.. . Restrictions on using GO TO • • • A GOTO statement cannot branch into an IF statement.. FOR i IN 1. END.an executable statement END LOOP.. END IF. or subblock. Also.. .

SQL Support in PL/SQL Data Manipulation Transaction Control SQL Functions SQL Pseudocolumns SQL Operators INSERT. UPDATE.. ROWID. A stub is dummy subprogram that allows you to defer the definition of a procedure or function until you test and debug the main program. amount REAL)IS BEGIN NULL. WHEN VALUE_ERROR THEN INSERT INTO errors VALUES . STDDEV. VARIANCE CURRVAL. however. SAVEPOINT. a GOTO statement can branch from an exception handler into an enclosing block. It can. WHEN OTHERS THEN NULL. However. • The NULL statement is a handy way to create stubs when designing applications from the top down. SET TRANSACTION AVG. The NULL Statement • The NULL statement explicitly specifies inaction. ROWNUM all comparison. MAX. COMMIT. ROLLBACK.Oracle PL/SQL • A GOTO statement cannot branch from an exception handler into the current block. NEXTVAL. MIN. LEVEL. COUNT.. END debit_account. END. DELETE. SELECT. it does nothing other than pass control to the next statement. Example : EXCEPTION WHEN ZERO_DIVIDE THEN ROLLBACK. improve readability. set. SUM. and row operators Jayashree Page 15 of 69 . LOCK TABLE COMMIT. • Example : PROCEDURE debit_account(acct_id INTEGER.

loc dept.first. A user-defined record and a %ROWTYPE record always have different data types You cannot use the INSERT statement to insert user-defined records into a database table. records of different types cannot be assigned to each other. dname dept. deptrec deptrectype.Oracle PL/SQL User-Defined Records • • The user can define logically related variables into a composite data type as records.dname%TYPE. Defining a RECORD type : TYPE type_name IS RECORD ( field_name1 field_type [NOT NULL {:= | DEFAULT} expr]. Even if the fields match exactly.). Jayashree Page 16 of 69 . • • • • User-Defined Records : Example TYPE deptrectype IS RECORD ( deptno dept.column%TYPE | table%ROWTYPE | cursor%ROWTYPE | cursor_variable%ROWTYPE} • • • To reference individual fields in a record.. Declaring Records : records must be declared in two steps .loc%TYPE ). use dot notation record_name. or nullity. field_name2 field_type [NOT NULL {:= | DEFAULT} expr]. inequality.deptno%TYPE. Records cannot be tested for equality. define a RECORD type.field_name Fields declared as NOT NULL must be initialized. . then declare user-defined records of that type.. where field_type stands for the following syntax: {datatype_name | variable%TYPE | record_variable%TYPE | table.

captain Employee. FUNCTION nth_highest_salary (n INTEGER) RETURN EmpRec IS . job_title VARCHAR2(15). hours SMALLINT).deptno := ….2)). dname. object types cannot have attributes of type RECORD.declare varray depart_time TimeRec. However.. -. salary REAL(7. dept_num INTEGER(2). . -. PL/SQL lets you define records that contain objects. To reference a field in deptrec : deptrec. DECLARE TYPE TimeRec IS RECORD ( seconds SMALLINT. plane_id VARCHAR2(10). and other records (called nested records). You can specify a RECORD type in the RETURN clause of a function specification..declare object passengers PassengerList. collections.declare nested record airport_code VARCHAR2(10)).. DECLARE TYPE EmpRec IS RECORD ( emp_id INTEGER last_name VARCHAR2(15). Jayashree Page 17 of 69 .Oracle PL/SQL To store data into deptrec : SELECT deptno. -. loc INTO deptrec FROM dept WHERE deptno = 10. TYPE FlightRec IS RECORD ( flight_no INTEGER.. minutes SMALLINT.

as both are made up of columns/fields. (T / F) 7. prior to its use in the body of the block. The user can define logically related variables into a composite data type as __________________________ Jayashree Page 18 of 69 . _______________________________ attribute can be used in PL/SQL to declare a variable to be of the same type as another variable or a table column. Initialization of variables cannot be done in the DECLARE part of a PL/SQL block. (T /F) 4. ________________________________________ statement allows for breaking out of a loop unconditionally. (T / F) 5.Oracle PL/SQL Review Questions 1. 2. The PL/SQL statement which helps in creating the stubs is _____________________ 6. (T / F) 3. Nesting of blocks is allowed in any portion of a PL/SQL block. A loop label or block label should be declared in the DECLARE section. A PL/SQL table is similar to a base table. 8.

Oracle PL/SQL Cursors Topics • • • • • • What are Cursors? Explicit Cursors Cursor Attributes Cursor FOR Loops Passing Parameters to Cursors Using Cursor Variables Jayashree Page 19 of 69 .

When a query returns multiple rows. sal FROM emp WHERE deptno = 10. subprogram. Syntax : CURSOR cursor-name IS select-statement. including queries that return only one row. You can use three commands to control a cursor: • OPEN • FETCH • CLOSE • • • Declaring a cursor : • • • When you declare a cursor. Example : DECLARE CURSOR c1 IS SELECT ename. A PL/SQL construct called a cursor lets you name a work area and access its stored information.Oracle PL/SQL What are Cursors? • • Oracle uses work areas to execute SQL statements and store processing information. you can explicitly declare a cursor to process the rows. You can declare a cursor in the declarative part of any PL/SQL block. one. depending on how many rows meet your search criteria. PL/SQL implicitly declares a cursor for all SQL data manipulation statements. you can explicitly declare a cursor to process the rows individually. you name it and associate it with a specific query. • • • Explicit Cursors • The set of rows returned by a query can consist of zero. or package. For queries that return more than one row. There are two kinds of cursors: implicit and explicit. Jayashree Page 20 of 69 . or multiple rows.

Syntax : OPEN cursor-name. there must be a corresponding variable in the INTO list. the cursor advances to the next row in the active set. Syntax : FETCH cursor-name INTO variables. Once a cursor is closed. • • • Closing a Cursor : • • • • The CLOSE statement disables the cursor. Example : FETCH c1 INTO my_ename. Syntax : CLOSE cursor-name. Example : CLOSE c1. my_sal. their data types must be compatible. you can reopen it. Also. For each column value returned by the query associated with the cursor.Oracle PL/SQL Opening a Cursor : • Opening the cursor executes the query and identifies the active set. For cursors declared using the FOR UPDATE clause. the OPEN statement also locks those rows. and the active set becomes undefined. After each fetch. which consists of all rows that meet the query search criteria. Example : OPEN c1. • • Fetching with a Cursor : • The FETCH statement retrieves the rows in the active set one at a time. Jayashree Page 21 of 69 . Any other operation on a closed cursor raises the predefined exception INVALID_CURSOR.

if last fetch succeeded Returns the number of rows fetched Evaluates to true. DELETE.Oracle PL/SQL Cursor Attributes Explicit Cursor Attributes • Each cursor or cursor variable has four attributes: %FOUND. and %ROWCOUNT. no more rows left Evaluates to true. %ISOPEN %NOTFOUND. or SELECT INTO statement. UPDATE. not the actual number of rows that satisfy the query. .e. if last fetch failed. When appended to the cursor or cursor variable. Is true if DML statement was not successful Is true if DML statement was successful Returns number of rows affected by a DML statement Is always false because ORACLE automatically closes an implicit cursor after executing its SQL statement SQL%NOTFOUND SQL%FOUND SQL%ROWCOUNT SQL%ISOPEN • If a SELECT INTO statement returns more than one row. these attributes return useful information about the execution of a data manipulation statement. PL/SQL raises the predefined exception TOO_MANY_ROWS and %ROWCOUNT yields 1. i. Evaluates to true. if the cursor is open • %NOTFOUND %FOUND %ROWCOUNT %ISOPEN Implicit Cursor Attributes • Implicit cursor attributes return information about the execution of an INSERT. Jayashree Page 22 of 69 .

and CLOSE statements. Syntax : FOR index IN cursor-name LOOP statements.Oracle PL/SQL Example: Update the salaries of all employees by 100 if the current salary is more than 1000. IF var_sal > 1000 THEN var_sal := var_sal + 100. LOOP FETCH c1 INTO var_empno. Note: 1. opens a cursor. FETCH. Using ‘WHERE CURRENT OF <cursor-name>’ in the above example speeds up the update since the condition is the same as the select. The individual values of the fields of the row in the record can be referenced by the dot notation: index. DECLARE var_empno emp. A cursor FOR loop implicitly declares its loop index as a %ROWTYPE record. CLOSE c1. you can simplify coding by using a cursor FOR loop instead of the OPEN. COMMIT. END IF. END LOOP. repeatedly fetches rows of values from the active set into fields in the record. dbms_output. Cursor FOR Loops • • In most situations that require an explicit cursor. Execute the following SQL*PLUS command prior to the use of dbms_output. EXIT WHEN c1%NOTFOUND. var_sal. sal FROM emp. BEGIN OPEN c1. and closes the cursor when all rows have been processed.put_line procedure: SQL> SET SERVEROUTPUT ON 2.column_name. UPDATE emp SET sal = var_sal WHERE empno = var_empno. var_sal emp.put_line(‘Salary updated for’ ||var_empno). CURSOR c1 IS SELECT empno.empno%type. • Jayashree Page 23 of 69 .sal%type. END. END LOOP.

END IF. END LOOP. higher_comm NUMBER(4) := 0. Passing Parameters to Cursors • • You can pass parameters to the cursor used in a cursor FOR loop. DECLARE CURSOR emp_cursor(dnum NUMBER) IS SELECT sal.n3).n2 / (c1rec. IF emp_record. Note: Using the COMMIT inside the loop closes the cursor. you determine how many employees have salaries higher than $2000 and how many have commissions larger than their salaries. Avoid it. total_wages NUMBER(11. IF emp_record. you compute the total wages paid to employees in that department.00 THEN high_paid := high_paid + 1.comm > emp_record.sal + emp_record. NULL. total_wages := total_wages + emp_record. BEGIN FOR emp_record IN emp_cursor(20) LOOP emp_record.comm. Also. you pass a department number. CURSOR c1 IS SELECT n1. BEGIN FOR c1rec IN c1 LOOP /* calculate and store the results */ result := c1rec. n2.2) := 0.sal THEN higher_comm := higher_comm + 1.sal > 2000.col1%TYPE.n1 + c1rec.comm. Then.comm := NVL(emp_record. n3 FROM data_table WHERE exper_num = 1. 0). Example : In the following example. NULL). high_paid NUMBER(4) := 0. COMMIT. INSERT INTO temp VALUES (result. Jayashree Page 24 of 69 . END IF.Oracle PL/SQL • Example : Cursor FOR Loop DECLARE result temp. END LOOP. END. comm FROM emp WHERE deptno = dnum.

COMMIT. A cursor variable has datatype REF CURSOR. you can assign new values to a cursor variable and pass it as a parameter to subprograms. Using Cursor Variables • Like a cursor. Syntax for defining: TYPE ref_type_name IS REF CURSOR RETURN return_type. declaring a cursor variable creates a pointer. But. END. then declare cursor variables of that type. Examples: DECLARE TYPE DeptCurTyp IS REF CURSOR RETURN dept%ROWTYPE. DECLARE TYPE EmpCurTyp IS REF CURSOR RETURN emp%ROWTYPE.weak Jayashree Page 25 of 69 . -.strong TYPE GenericCurTyp IS REF CURSOR. you take two steps. Whereas a cursor is static. dept_cv DeptCurTyp. Cursor variables are like C or Pascal pointers. you define a REF CURSOR type. 'Total Wages: ' || TO_CHAR(total_wages)).declare cursor variable -. • • Defining REF CURSOR Types To create cursor variables. higher_comm. a cursor variable points to the current row in the result set of a multirow query. You can open a cursor variable for any type-compatible query. which hold the memory location (address) of some item instead of the item itself. This gives you an easy way to centralize data retrieval.Oracle PL/SQL INSERT INTO temp VALUES (high_paid. This gives you more flexibility. including subprograms stored in an Oracle database. a cursor variable is dynamic because it is not tied to a specific query. not an item. Declaring Cursor Variables DECLARE TYPE DeptCurTyp IS REF CURSOR RETURN dept%ROWTYPE. Also. First. So. cursors differ from cursor variables the way constants differ from variables. -.

FETCH..Oracle PL/SQL DECLARE TYPE TmpCurTyp IS REF CURSOR RETURN emp%ROWTYPE. Opening a Cursor Variable The OPEN-FOR statement associates a cursor variable with a multi-row query. -.declare cursor variable TYPE EmpCurTyp IS REF CURSOR RETURN tmp_cv%ROWTYPE. sal NUMBER(7.declare cursor variable DECLARE TYPE EmpRecTyp IS RECORD ( empno NUMBER(4). executes the query.2)). ename VARCHAR2(1O).. • Cursor variables do not take parameters • The query cannot be FOR UPDATE Examples: IF NOT emp_cv%ISOPEN THEN /* Open cursor variable. You need not close a cursor variable before reopening it. -. END emp_data. Note: Other OPEN-FOR statements can open the same cursor variable for different queries. END IF. PROCEDURE open_emp_cv (emp_cv IN OUT EmpCurTyp) IS .. emp_cv EmpCurTyp. */ OPEN emp_cv FOR SELECT * FROM emp. When you reopen a cursor variable for a different query. tmp_cv TmpCurTyp. Jayashree Page 26 of 69 . The statement syntax is OPEN {cursor_variable_name | :host_cursor_variable_name} FOR select_statement.declare cursor variable DECLARE TYPE EmpCurTyp IS REF CURSOR RETURN emp%ROWTYPE. and CLOSE. emp_cv EmpCurTyp. -. TYPE EmpCurTyp IS REF CURSOR RETURN EmpRecTyp. PROCEDURE open_emp_cv (emp_cv IN OUT EmpCurTyp). CREATE PACKAGE emp_data AS . and identifies the result set.. TYPE EmpCurTyp IS REF CURSOR RETURN emp%ROWTYPE. the previous query is lost. Controlling Cursor Variables: You use three statements to control a cursor variable: OPEN-FOR.

. The statement syntax follows: CLOSE {cursor_variable_name | :host_cursor_variable_name). END open_emp_cv. OUT EmpCurTyp. variable_name]. sal > 2500. Jayashree Page 27 of 69 . END emp_data. Closing a Cursor Variable The CLOSE statement disables a cursor variable. PROCEDURE open_emp_cv (emp_cv IN OUT EmpCurTyp. choice IN NUMBER). NUMBER) IS comm IS NOT NULL. Example CREATE PACKAGE emp_data AS TYPE GenericCurTyp IS REF CURSOR. END open_emp_cv. TYPE EmpCurTyp IS REF CURSOR RETURN emp%ROWTYPE. the associated result set is undefined. PROCEDURE open_emp_cv (emp_cv IN OUT EmpCurTyp) IS BEGIN OPEN emp_cv FOR SELECT * FROM emp. deptno = 20. | record_name}. Fetching from a Cursor Variable The FETCH statement retrieves rows one at a time from the result set of a multi-row query.. END emp_data. The statement syntax follows: FETCH {cursor_variable_name | :host_cursor_variable_name} INTO {variable_name[. CREATE PACKAGE BODY emp_data AS PROCEDURE open_emp_cv (emp_cv IN choice IN BEGIN IF choice = 1 THEN OPEN emp_cv FOR SELECT * FROM emp WHERE ELSIF choice = 2 THEN OPEN emp_cv FOR SELECT * FROM emp WHERE ELSIF choice = 3 THEN OPEN emp_cv FOR SELECT * FROM emp WHERE END IF.Oracle PL/SQL CREATE PACKAGE BODY emp_data AS . After that. END emp_data...

dept WHERE emp. job. job_title CHAR(9).deptno = dept_no AND emp. / COLUMN EMPNO HEADING Number COLUMN ENAME HEADING Name COLUMN JOB HEADING JobTitle COLUMN DNAME HEADING Department COLUMN LOC HEADING Location SET AUTOPRINT ON VARIABLE cv REFCURSOR EXECUTE emp_data. emp_cv IN OUT EmpCurTyp) IS BEGIN OPEN emp_cv FOR SELECT empno. dept_name CHAR(14). END.Oracle PL/SQL Example: Using a bind variable CREATE PACKAGE emp_data AS TYPE EmpRecTyp IS RECORD ( emp_id NUMBER(4). END. ename. END.deptno ORDER BY empno. :cv) Jayashree Page 28 of 69 . emp_name CHAR(10). dname.deptno = dept. loc FROM emp. emp_cv IN OUT EmpCurTyp). / CREATE PACKAGE BODY emp_data AS PROCEDURE get_staff (dept_no IN NUMBER. PROCEDURE get_staff (dept_no IN NUMBER.get_staff(20. dept_loc CHAR(13)). TYPE EmpCurTyp IS REF CURSOR RETURN EmpRecTyp.

including queries that return multiple rows. Jayashree Page 29 of 69 . Write an anonymus PL/SQL block that retrieves the five highest paid employees from the EMP table. Consider two tables having a column each of numbers. The two kinds of cursors are _____________________________________________ 3. The name of the implicit cursor is _______________________________________ 7. The explicit cursor attribute which evaluates to true if the last fetch succeeded is _______________________________________________________ Exercises 1.Oracle PL/SQL Review Questions 1. The SELECT statement used in a PL/SQL block need not necessarily have an INTO clause always. and 20% to all salesmen. 2. PL/SQL implicitly declares a cursor for all DML statements. give a raise in sal of 10% to all clerks. The PL/SQL statement that executes the query associated with a cursor is _____________________________________________ 5. (T / F) 6. Write these increments in a separate table. Get a number from each of the two tables. then insert the sum of the rows into a third table. 3. Stop when all rows have been fetched from either of the two tables. (T / F) 4. You can use the _______________________________________________ packaged procedure to output something to the screen. 2. In the EMP table. as well as update in the EMP table.

Oracle PL/SQL Processing Transactions in PL/SQL Topics • • Processing Transactions Overriding Default Locking – – Using the FOR UPDATE Clause Using the LOCK TABLE Command Jayashree Page 30 of 69 .

once a query begins and as it proceeds. The COMMIT statement releases all row and table locks.Oracle PL/SQL Processing Transactions • When a table is being queried by one user and updated by another at the same time. Until you commit the changes. Oracle is transaction oriented. they see the data as it was before you made the changes. Oracle takes snapshots of the table's data and records changes in a rollback segment. Oracle treats the series of SQL statements as a unit so that all the changes brought about by the statements are either committed (made permanent) or rolled back (undone) at the same time. A transaction is a series of one or more logically related SQL statements that accomplish a task. other users cannot access the changed data. It also erases any savepoints marked since the last commit or rollback. A lock gives you temporary ownership of a database resource such as a table or row of data. the data read by the query does not change. If your program fails in the middle of a transaction. • • • • • • Jayashree Page 31 of 69 . the database is automatically restored to its former state. That is. The COMMIT statement ends the current transaction and makes permanent any changes made during that transaction. Oracle generates a read-consistent view of the data for the query. every SQL statement is part of a transaction. Oracle uses information in the rollback segment to build read-consistent query results and to undo changes if necessary. the next SQL statement automatically begins another transaction. However. Thus. Oracle uses locks to control concurrent access to data. you can request data locks on tables or rows when it is to your advantage to override default locking. As update activity continues. it uses transactions to ensure data integrity. When one transaction ends. All the SQL statements executed since the last commit or rollback make up the current transaction. The first SQL statement in your program begins a transaction. that is. You can choose from several modes of locking such as row share and exclusive. data cannot be changed by other users until you finish with it. Thus. The COMMIT and ROLLBACK statements ensure that all database changes brought about by SQL operations are either made permanent or undone at the same time. You need never explicitly lock a resource because default locking mechanisms protect Oracle data and structures.

The number of active savepoints per session is unlimited. if you make a mistake like deleting the wrong row from a table. PL/SQL does not assign values to OUT parameters. FROM new_emp WHERE . Rolling back is useful for two reasons. if you start a transaction that you cannot finish because an exception is raised or a SQL statement fails. .Oracle PL/SQL • The ROLLBACK statement ends the current transaction and undoes any changes made during that transaction.. a rollback lets you return to the starting point to take corrective action and perhaps try again. . INSERT INTO tax VALUES (emp_id... INSERT INTO pay VALUES (emp_id.. If the statement fails. any savepoints marked after that savepoint are erased.. savepoints let you undo parts of a transaction instead of the whole transaction. END. Example: DECLARE emp_id INTEGER.). PL/SQL does not roll back database work done by the subprogram.. . UPDATE... If you exit a stored subprogram with an unhandled exception. Oracle marks an implicit savepoint (unavailable to you). or DELETE statement. INTO emp_id... Implicit Rollbacks : Before executing an INSERT.. Also. First. . When you roll back to a savepoint.). Oracle rolls back to the savepoint. the savepoint to which you roll back is not erased. a rollback restores the original data. • SAVEPOINT names and marks the current point in the processing of a transaction... Second. Used with the ROLLBACK TO statement.. INSERT INTO emp VALUES (emp_id. • • • • Jayashree Page 32 of 69 . . . EXCEPTION WHEN DUP_VAL_ON_INDEX THEN ROLLBACK....). BEGIN SELECT empno. . However.. .

WHERE empno = emp_id. When querying multiple tables. • Using the FOR UPDATE Clause DECLARE CURSOR c1 IS SELECT empno.empno%TYPE. use the FOR UPDATE clause only if you want to lock the rows before the update or delete.... In that case. EXCEPTION WHEN DUP_VAL_ON_INDEX THEN ROLLBACK TO do_insert. Oracle automatically obtains row-level locks at update or delete time. you can explicitly lock specific rows of a table to make sure they do not change before an update or delete is executed. not as they are fetched. .. Rows in a table are locked only if the FOR UPDATE OF clause refers to a column in that table. So. All rows are locked when you open the cursor.Oracle PL/SQL Example: DECLARE emp_id emp. sal FROM emp WHERE job = 'SALESMAN' AND comm > sal FOR UPDATE. Overriding Default Locking • With the SELECT FOR UPDATE statement..... You can explicitly lock entire tables using the LOCK TABLE statement. . However. SAVEPOINT do_insert. you can use the FOR UPDATE clause to confine row locking to particular tables. INSERT INTO emp VALUES (emp_id.. • The FOR UPDATE clause identifies the rows that will be updated or deleted.). you must make sure that the row is not changed by another user before the update. • • Jayashree Page 33 of 69 . UPDATE emp SET . you cannot fetch from a FOR UPDATE cursor after a commit. then locks each row in the active set.. The rows are unlocked when you commit or roll back the transaction. This is useful when you want to base an update on the existing values in a row. DELETE FROM emp WHERE . END. So. BEGIN .

if the table has been locked by another user. END. dept WHERE emp. . The optional keyword NOWAIT tells Oracle not to wait. Only if two different transactions try to modify the same row will one transaction wait for the other to complete. • Jayashree Page 34 of 69 . sal.. and a query never acquires a table lock.deptno = dept.. BEGIN OPEN c1. END LOOP. Table locks are released when your transaction issues a commit or rollback.deptno FOR UPDATE OF sal. LOOP FETCH c1 INTO . sal FROM emp FOR UPDATE. Using the CURRENT OF clause You can use the CURRENT OF clause in UPDATE or DELETE statement to refer to the latest row fetched from a cursor : DECLARE CURSOR c1 IS SELECT empno. they prevent other users from locking the entire table for exclusive use. ... A table lock never keeps other users from querying a table.. . Row share locks allow concurrent access to a table.Oracle PL/SQL • Example : DECLARE CURSOR c1 IS SELECT ename. dname FROM emp.. the statement below locks the emp table in row share mode.. Using the LOCK TABLE Command • The LOCK TABLE statement can be used to lock entire database tables in a specified lock mode so that you can share or deny access to them. UPDATE emp SET sal = new_sal WHERE CURRENT OF c1. For example. LOCK TABLE emp IN ROW SHARE MODE NOWAIT.. job.

Oracle PL/SQL Error Handling in PL/SQL Topics • • • • • • Exceptions Scope Rules Using EXCEPTION_INIT Propagation of Exception Re-raising an Exception SQLCODE and SQLERRM Jayashree Page 35 of 69 .

If there is no enclosing block. you try to open an already open cursor. you try to assign values to the attributes of an uninitialized (atomically null) object. you cannot open that cursor inside the loop.. That is. the current block stops executing and the enclosing block resumes with the next statement. a warning or error condition is called an exception. you you try to apply collection methods other than EXISTS to an uninitialized (atomically null) nested table or varray. which can also raise predefined exceptions. or you try to assign values to the elements of an uninitialized nested table or varray. In procedural statements. you try to store duplicate values in a database column that is constrained by a unique index. Internal exceptions are raised implicitly (automatically) by the runtime system.Oracle PL/SQL Exceptions • In PL/SQL. in a SQL statement. So. normal execution stops and the control transfers to the exception-handling part of your PL/SQL block or subprogram. A cursor FOR loop automatically opens the cursor to which it refers. you try an illegal cursor operation such as closing an unopened cursor. the convertion of character string to a number fails because the character string does not represent a valid number. Exceptions can be internally defined (by the runtime system) or user defined. CURSOR_ALREADY_OPEN DUP_VAL_ON_INDEX INVALID_CURSOR INVALID_NUMBER Jayashree Page 36 of 69 . control returns to the host environment. After an exception handler runs.. To handle raised exceptions. When an error occurs. User-defined exceptions must be raised explicitly by RAISE statements. You must close a cursor before you can reopen it. VALUE_ERROR is raised. an exception is raised. you write separate routines called exception handlers. • • • • • Pre-Defined Exceptions Exception ACCESS_INTO_NULL COLLECTION_IS_NULL Raised when .

For example. Jayashree Page 37 of 69 . The FETCH statement is expected to return no rows eventually. when you pass an open host cursor variable to a stored subprogram. so when that happens. INVALID_NUMBER is raised. SQL group functions such as AVG and SUM always return a value or a null. VALUE_ERROR is raised if the conversion of a character string to a number fails. or you reference a deleted element in a nested table. if the value is longer than the declared length of the variable. the return types of the actual and formal parameters must be compatible. or sizeconstraint error occurs. you reference a nested table or varray element using an index number that is outside the legal range (-1 for example).Oracle PL/SQL LOGIN_DENIED NO_DATA_FOUND NOT_LOGGED_ON PROGRAM_ERROR ROWTYPE_MISMATCH STORAGE_ERROR SUBSCRIPT_BEYOND_COUNT SUBSCRIPT_OUTSIDE_LIMIT TIMEOUT_ON_RESOURCE TOO_MANY_ROWS VALUE_ERROR ZERO_DIVIDE you try logging on to Oracle with an invalid username and/or password. an arithmetic. a timeout occurs while Oracle is waiting for a resource. PL/SQL aborts the assignment and raises VALUE_ERROR. your PL/SQL program issues a database call without being connected to Oracle. no exception is raised. conversion. In SQL statements. you reference a nested table or varray element using an index number larger than the number of elements in the collection. PL/SQL runs out of memory or memory is corrupted. or you reference an uninitialized element in an index-by table. the host cursor variable and PL/SQL cursor variable involved in an assignment have incompatible return types. In procedural statements. So. truncation. when you select a column value into a character variable. you try to divide a number by zero. PL/SQL has an internal problem. a SELECT INTO statement returns no rows. For example. a SELECT INTO statement that calls a group function will never raise NO_DATA_FOUND. a SELECT INTO statement returns more than one row.

… EXCEPTION WHEN out_of_stock THEN /* Exception Handling END. enclosing blocks cannot reference exceptions declared in a sub-block.. Because a block can reference only local or global exceptions. code */ Example : DECLARE acct_type INTEGER. 3) THEN RAISE INVALID_NUMBER. q_o_h NUMBER(5).exception_name • • Jayashree Page 38 of 69 .Oracle PL/SQL User-Defined Exceptions : Example : DECLARE out_of_stock EXCEPTION. the sub-block cannot reference the global exception unless it was declared in a labeled block.. declare the same exception in two different blocks. BEGIN . -. So. … BEGIN … IF q_o_h < 1 THEN RAISE out_of_stock.. IF acct_type NOT IN (1. . END. Scope Rules • You cannot declare an exception twice in the same block. Exceptions declared in a block are considered local to that block and global to all its sub-blocks. You can.. If you redeclare a global exception in a sub-block.. 2. . however. in which case the following syntax is valid: block_label. EXCEPTION WHEN INVALID_NUMBER THEN ROLLBACK. END IF. the local declaration prevails.raise predefined exception END IF..

PRAGMA EXCEPTION_INIT(deadlock_detected. where exception_name is the name of a previously declared exception. EXCEPTION WHEN deadlock_detected THEN -. Jayashree Page 39 of 69 . Example: DECLARE deadlock_detected EXCEPTION. the pragma EXCEPTION_INIT tells the compiler to associate an exception name with an Oracle error number. That allows you to refer to any internal exception by name and to write a specific handler for it. That is. which can be thought of as a parenthetical remark to the compiler. In PL/SQL. you must use the OTHERS handler or the pragma EXCEPTION_INIT... -60). if PL/SQL cannot find a handler for it in the current block or subprogram.Oracle PL/SQL Using EXCEPTION_INIT • To handle unnamed internal exceptions. END. Pragmas (also called pseudoinstructions) are processed at compile time. BEGIN . Oracle_error_number). subprogram. In the latter case. the exception propagates. or package using the syntax • • PRAGMA EXCEPTION_INIT(exception_name.. the exception reproduces itself in successive enclosing blocks until a handler is found or there are no more blocks to search. You can code the pragma EXCEPTION_INIT in the declarative part of a PL/SQL block. A pragma is a compiler directive. PL/SQL returns an unhandled exception error to the host environment.. not at run time.handle the error . Propagation of Exception • When an exception is raised.

then pass it to an enclosing block.. • Jayashree Page 40 of 69 . simply place a RAISE statement in the local handler without an exception name. END IF.. enclosing blocks cannot reference exceptions declared in a sub-block.sub-block ends EXCEPTION .Oracle PL/SQL • An exception can propagate beyond its scope. BEGIN ... Example : BEGIN .. then log the error in an enclosing block. you want to re raise an exception. according to the scope rules. So. only an OTHERS handler can catch the exception. beyond the block in which it was declared. THEN RAISE past_due. you might want to roll back a transaction in the current block.. For example. it propagates to the enclosing block. Re-raising an Exception • Sometimes.sub-block begins past_due EXCEPTION. END. END. that is. WHEN OTHERS THEN ROLLBACK. DECLARE ---------.. IF . that is. handle it locally. • Because the block in which it was declared has no handler for the exception named past_due.. To re raise an exception. But. ------------.

sub-block ends EXCEPTION WHEN out_of_balance THEN -.handle the error RAISE.sub-block begins .. SQLCODE and SQLERRM • In an exception handler... in which case SQLCODE returns +100. THEN RAISE out_of_balance. BEGIN ---------. The number that SQLCODE returns is negative unless the Oracle error is no data found. SQLCODE returns +1 and SQLERRM returns the message User-Defined Exception If no exception has been raised.. SQLCODE returns the number of the Oracle error.. For internal exceptions. For user-defined exceptions.handle the error differently .Oracle PL/SQL DECLARE out_of_balance EXCEPTION. -. SQLERRM returns the corresponding error message. END... you can use the functions SQLCODE and SQLERRM to find out which error occurred and to get the associated error message. IF . END. successful completion • • • Jayashree Page 41 of 69 . EXCEPTION WHEN out_of_balance THEN -. BEGIN .. SQLCODE returns zero and SQLERRM returns the message : ORA-0000: normal. -..raise the exception END IF. -----------..reraise the current exception . The message begins with the Oracle error code.

. END. WHEN OTHERS THEN err_num := SQLCODE. END LOOP. trantype.qoh%TYPE := 0.. INSERT INTO errors VALUES (err_num. END. BEGIN .. 100). Make sure you pass negative error numbers to SQLERRM. err_msg VARCHAR2(100). then use the variables in the SQL statement.. EXCEPTION . • Example: To update the ITEMMAST table using the ITTRAN table DECLARE CURSOR t1 IS SELECT itno. BEGIN . you must assign their values to local variables. trandate.err_msg). DECLARE err_msg VARCHAR2(100). INSERT INTO errors VALUES (err_msg). 1. You cannot use SQLCODE or SQLERRM directly in a SQL statement. */ FOR err_num IN 1.Oracle PL/SQL • You can pass an error number to SQLERRM.. /* Get all Oracle error messages. err_msg := SUBSTR(SQLERRM. Instead.. . BEGIN FOR tran IN t1 LOOP /* inner block */ DECLARE out_of_stock EXCEPTION.itno.9999 LOOP err_msg := SQLERRM(-err_num).. Jayashree Page 42 of 69 ... in which case SQLERRM returns the message associated with that error number. as the following example shows: DECLARE err_num NUMBER. var_qoh itemmast. qty FROM ittran WHERE upper(updt) = ‘N’ ORDER BY itno. BEGIN SELECT qoh INTO var_qoh FROM itemmast WHERE itno = tran.

ELSE UPDATE itemmast SET qoh = qoh + tran.qty > var_qoh THEN RAISE out_of_stock. END.trantype = ‘I’ THEN IF tran.‘invalid item number’). tran. ‘out of stock’ ). UPDATE ittran SET updt = ‘Y’ WHERE itno = tran.Oracle PL/SQL IF tran.qty.itno.tran.trantype. Jayashree Page 43 of 69 . tran.qty WHERE itno = tran.qty.itno. EXCEPTION WHEN out_of_stock THEN INSERT INTO errortab VALUES (tran. END IF.itno. /* inner block */ END LOOP.itno.trantype. ELSE UPDATE itemmast SET qoh = qoh . WHEN no_data_found THEN INSERT INTO errortab VALUES (tran.itno. tran.trandate. tran.qty WHERE itno = tran. tran. /* FOR loop */ /* main block */ END. END IF.trandate. tran.

Oracle PL/SQL Review Questions 1. you can use the function ___________________ Exercises 1. A routine that is used to handle raised exceptions is called ____________________ ______________________________________ 3. Consider the following tables : ITEMMAST ITNO NAME QOH (Quantity on hand) CLASS (Category) UOM (Unit of measurement) ROL (Re-order level) ROQ (Re-order quantity) RATE ITTRAN ITEMNO TRANTYPE TRANQTY TRANDATE UPDT Update the itemmast table using the ittran table. To get the error message of an error. The exception handler which can catch any kind of exception raised is called ___________________________ 7. (T / F) 2.(T / F) 4. Jayashree Page 44 of 69 . You can use an explicit GO TO statement in the exception handling part of a PL/SQL block to go back to the statement following the one which raised the exception. The internal exception DUP_VAL_ON_INDEX means ______________________ ___________________________________________________________________ 5. Record all invalid transactions in another table. Internal exceptions cannot be raised by the RAISE statement. The internal exception TOO_MANY_ROWS is raised when __________________ ___________________________________________________________________ 6.

Each row in the action table contains an account number. Suppose there are the two tables : ACCOUNTS Account_id 1 2 3 4 5 Balance 1000 2000 1500 6500 500 ACTION Account_id 3 6 5 7 1 9 10 Oper_type u i d u I d x New_value 599 20099 1599 399 Status Time_tag 12-DEC-97 12-DEC-97 12-DEC-97 12-DEC-97 12-DEC-97 12-DEC-97 12-DEC-97 Accounts table is modified according to instructions stored in the action table. or D for insert. if the account already exists. On an insert. U. Jayashree Page 45 of 69 . if the row does not exist. it is created by an insert. no action is taken. or delete). and a time tag used to sequence the transactions. On a delete. an action to be taken (I. an update is done instead. if the account does not exist. On an update.Oracle PL/SQL 2. an amount by which to update the account. In each case the status is written into the action table. update.

Oracle PL/SQL Subprograms and Packages Topics • • • • • • • • • • • • What are Subprograms? Procedures Functions Declaring Subprograms Stored Subprograms Positional and Named Notation Overloading Recursion Packages Package STANDARD Product-Specific Packages Advantages of Packages Jayashree Page 46 of 69 .

and an optional exceptionhandling part. END IF. you use a procedure to perform an action and a function to compute a value. Jayashree Page 47 of 69 . control execution. overdrawn EXCEPTION. END debit_account. an executable part. IF new_balance < 0 THEN RAISE overdrawn. • • • • • • Subprograms : Example PROCEDURE debit_account (acct_id INTEGER. cursors.. new_balance REAL. PL/SQL has two types of subprograms . BEGIN SELECT bal INTO old_balance FROM accts WHERE acctno = acct_id. Subprograms have a declarative part. exceptions.functions Generally. These objects are local and cease to exist when you exit the subprogram. constants. and manipulate Oracle data..procedures . The declarative part contains declarations of types. The exception-handling part contains exception handlers. ELSE UPDATE accts SET bal = new_balance WHERE acctno = acct_id. new_balance := old_balance . which deal with exceptions raised during execution. EXCEPTION WHEN overdrawn THEN . amount REAL) IS old_balance REAL.amount. variables. and nested subprograms.Oracle PL/SQL What are Subprograms? • Subprograms are named PL/SQL blocks that can take parameters and can be invoked. The executable part contains statements that assign values.

BEGIN SELECT sal INTO current_salary FROM emp WHERE empno = emp_id. parameter. END raise_salary. Jayashree Page 48 of 69 . where parameter stands for the following syntax: parameter_name [IN|OUT|IN OUT] datatype [{:=|DEFAULT} expr] • You cannot specify a constraint on the datatype.])] IS [local declarations] BEGIN executable statements [EXCEPTION exception handlers] END [name]. EXCEPTION WHEN NO_DATA_FOUND THEN INSERT INTO emp_audit VALUES (emp_id. Example : Procedure PROCEDURE raise_salary (emp_id INTEGER.Oracle PL/SQL Procedures Syntax : PROCEDURE name [(parameter[.. 'Salary is null'). END IF.. . ELSE UPDATE emp SET sal = sal + increase WHERE empno = emp_id. IF current_salary IS NULL THEN RAISE salary_missing. salary_missing EXCEPTION. WHEN salary_missing THEN INSERT INTO emp_audit VALUES (emp_id. 'No such number'). increase REAL) IS current_salary REAL.

parameter. Inside the subprogram. • Jayashree Page 49 of 69 .. Inside the subprogram. an OUT parameter acts like an uninitialized variable. its value cannot be assigned to another variable or reassigned to itself. . you cannot specify a constraint on the data type. Therefore. RETURN (salary >= min_sal) AND (salary <= max_sal). an IN OUT parameter acts like an initialized variable. max_sal REAL. BEGIN SELECT losal.Oracle PL/SQL Functions Syntax : FUNCTION name [(parameter[. it can be assigned a value and its value can be assigned to another variable. IN OUT Mode : An IN OUT parameter lets you pass initial values to the subprogram being called and return updated values to the caller. title CHAR) RETURN BOOLEAN IS min_sal REAL. Example : Function The following function determines if an employee salary is out of range: FUNCTION sal_ok (salary REAL. max_sal FROM sals WHERE job = title. IN parameters can be initialized to default values. an IN parameter acts like a constant. where parameter stands for the following syntax: parameter_name [IN | OUT | IN OUT] datatype [{:= | DEFAULT} expr] Note. Therefore. Inside the subprogram. hisal INTO min_sal. END sal_ok.])] RETURN datatype IS [local declarations] BEGIN executable statements [EXCEPTION exception handlers] END [name]. Therefore.. it cannot be assigned a value. Parameter Modes • IN Mode : An IN parameter lets you pass values to the subprogram being called. • OUT Mode : An OUT parameter lets you return values to the caller of a subprogram.

.Oracle PL/SQL Declaring Subprograms • You can declare subprograms in any PL/SQL block. However.. Therefore. PROCEDURE calc_rating ( . ) IS BEGIN . END.forward declaration .. ). DECLARE rating NUMBER. DECLARE PROCEDURE calc_rating ( .. CURSOR c1 IS SELECT * FROM emp.define mutually recursive subprograms .) BEGIN .. or package.group subprograms in a package A forward declaration consists of a subprogram specification terminated by a semicolon.. ) IS BEGIN calc_rating( . . you must declare subprograms at the end of a declarative section after all other program objects. */ PROCEDURE award_bonus ( .define subprograms in logical or alphabetical order .... you must declare a subprogram before calling it. END. PL/SQL requires that you declare an identifier before using it. Forward Declarations :You can use forward declarations to .. • • • Jayashree Page 50 of 69 .. ).. /* Define subprograms in alphabetical order. END.... PROCEDURE award_bonus (.. subprogram. -...

iss_qty NUMBER) AS BEGIN UPDATE itemmast SET qoh = qoh .Oracle PL/SQL Stored Subprograms • To create subprograms and store them permanently in an Oracle database. or can be executed directly at the SQL*PLUS prompt using the EXECUTE command : SQL> EXECUTE issue_qty ( 6.iss_qty WHERE itno = iss_item. 100 ) Actual and Formal Parameters • • Subprograms pass information using the parameters. Though not necessary. • • • Jayashree Page 51 of 69 .itno%TYPE. the actual parameters are evaluated and the result values are assigned to the corresponding formal parameters. Example : CREATE OR REPLACE PROCEDURE issue_qty ( iss_item itemmast. The variables or expressions referenced in the parameter list of a subprogram call are actual parameters. it is good programming practice to use different names for actual and formal parameters. When you call procedure raise_salary. which you can execute interactively from SQL*Plus. you use the CREATE PROCEDURE and CREATE FUNCTION statements. The variables declared in a subprogram specification and referenced in the subprogram body are formal parameters. END. • The stored subprograms can be either called from a PL/SQL program or other subprogram. COMMIT.

amount REAL) IS BEGIN . TYPE RealTabTyp IS TABLE OF REAL INDEX BY BINARY_INTEGER. amt REAL. you can use the same name for several different subprograms as long as their formal parameters differ in number. PROCEDURE credit (acctno INTEGER.n LOOP tab(i) := SYSDATE.credit(acct.credit(amount => amt. Example Suppose you want to initialize the first n rows in two index-by tables that were declared as follows: DECLARE TYPE DateTabTyp IS TABLE OF DATE INDEX BY BINARY_INTEGER. acctno => acct).credit(acctno => acct. Jayashree Page 52 of 69 . amount => amt). amt). -.mixed notation • Overloading • PL/SQL lets you overload subprogram names. -. END LOOP. sal_tab RealTabTyp..positional notation . Example : DECLARE acct INTEGER. hiredate_tab DateTabTyp. order. you can indicate the association between an actual and formal parameter by position or name. Procedure to initialize the index-by table named hiredate_tab: PROCEDURE initialize (tab OUT DateTabTyp..named notation .Oracle PL/SQL Positional and Named Notation • When calling a subprogram.credit(acct. -. you can call the procedure credit in four logically equivalent ways: .. END initialize. That is. n INTEGER) IS BEGIN FOR i IN 1.named notation . amount => amt). -. or data type family. END.

BEGIN indx := 50. comm_tab RealTabTyp..calls second version . hiredate_tab DateTabTyp. • Only local or packaged subprograms can be overloaded. Finally. you cannot overload two functions that differ only in return type (the data type of the result value) even if the types are in different families. you cannot overload two subprograms if their formal parameters differ only in subtype and the different subtypes are based on types in the same family. Also.n LOOP tab(i) := 0. END LOOP. You can place the two overloaded initialize procedures in the same block. initialize(hiredate_tab.. TYPE RealTabTyp IS TABLE OF REAL INDEX BY BINARY_INTEGER. or package. you cannot overload two subprograms if their formal parameters differ only in name or parameter mode. You cannot overload two subprograms if their formal parameters differ only in data type and the different data types are in the same family. indx BINARY_INTEGER. indx). DECLARE TYPE DateTabTyp IS TABLE OF DATE INDEX BY BINARY_INTEGER. PL/SQL determines which of the two procedures is being called by checking their formal parameters.Oracle PL/SQL Procedure to initialize the index-by table named sal_tab: PROCEDURE initialize (tab OUT RealTabTyp. END. you cannot overload standalone subprograms. -. END initialize. • • • Jayashree Page 53 of 69 . Therefore. -.. Likewise. . n INTEGER) IS BEGIN FOR i IN 1. indx)..0. subprogram.calls first version initialize(comm_tab..

Packages usually have two parts. -. it declares the types. cursors.public type and object declarations -. variables. although sometimes the body is unnecessary. and subprograms available for use.Oracle PL/SQL Recursion • PL/SQL supports recursive subprograms .subprogram specifications END [name]. ELSE RETURN n * fac(n . The specification is the interface to your applications. Packages • A package is a database object that groups logically related PL/SQL types. END fac. The body fully defines cursors and subprograms.returns n! BEGIN IF n = 1 THEN -.1).terminating condition RETURN 1. Jayashree Page 54 of 69 . and so implements the specification. Unlike subprograms. exceptions. you use the CREATE PACKAGE and CREATE PACKAGE BODY statements.recursive call END IF. objects. packages cannot be called. which you can execute interactively from SQL*PLUS : • • • • • CREATE PACKAGE name AS -. a specification and a body. and subprograms. To create packages and store them permanently in an Oracle database. parameterized. Example : FUNCTION fac (n POSITIVE) RETURN INTEGER IS -.specification (visible part) -. constants. or nested.

PROCEDURE hire_employee ( ename VARCHAR2.private type and object declarations -. • Application Package Database Specificatio Body Example : Package CREATE PACKAGE emp_actions AS -. Jayashree Page 55 of 69 .specification TYPE EmpRecTyp IS RECORD(emp_id INTEGER. sal NUMBER.Oracle PL/SQL CREATE PACKAGE BODY name AS -. comm NUMBER.initialization statements] END [name]. enhance. deptno NUMBER). salary REAL). You can debug. CURSOR desc_salary RETURN EmpRecTyp.subprogram bodies [BEGIN -. Package Interface • The specification holds public declarations. or replace a package body without changing the interface (package specification) to the package body.body (hidden part) -. PROCEDURE fire_employee (emp_id NUMBER). The body holds implementation details and private declarations. which are visible to your application. END emp_actions. mgr NUMBER. job VARCHAR2. which are hidden from your application.

mgr NUMBER. mgr. ename.subprogram_name You can reference package contents from a database trigger. END fire_employee. job VARCHAR2.NEXTVAL.object_name .body CURSOR desc_salary RETURN EmpRecTyp IS SELECT empno.Oracle PL/SQL CREATE PACKAGE BODY emp_actions AS -. sal NUMBER. as follows: . you use dot notation. sal FROM emp ORDER BY sal DESC. a stored subprogram. sal. job. or an Oracle tool such as SQL*Plus.package_name. END emp_actions. deptno NUMBER) IS BEGIN INSERT INTO emp VALUES (empno_seq. comm NUMBER. deptno). Referencing Package Contents • To reference the types.type_name . comm. PROCEDURE fire_employee (emp_id NUMBER) IS BEGIN DELETE FROM emp WHERE empno = emp_id. SYSDATE. END hire_employee.package_name. and subprograms declared within a package specification.package_name. • Jayashree Page 56 of 69 . PROCEDURE hire_employee ( ename VARCHAR2. objects.

If you redeclare ABS in a PL/SQL program. Package DBMS_ALERT : lets you use database triggers to alert an application when specific database values change. STANDARD. Package DBMS_OUTPUT : enables you to display output from PL/SQL blocks and subprograms. package STANDARD declares the following built-in function named ABS. exceptions. • • • Jayashree Page 57 of 69 . ORACLE Product-specific Packages • Package DBMS_STANDARD : provides language facilities that help your application interact with Oracle. which are available automatically to every PL/SQL program. Most built-in functions are overloaded. which makes it easier to test and debug them.. For example. you can report errors to an application and avoid returning unhandled exceptions.ABS(x) .. right VARCHAR2) RETURN VARCHAR2. That way. a procedure named raise_application_error lets you issue user-defined error messages. you can still call the built-in function by using dot notation. For example.. However. which returns the absolute value of its argument: FUNCTION ABS (n NUMBER) RETURN NUMBER. as follows: . You display the information by calling the procedure get_line or by using the command SET SERVEROUTPUT ON in SQL*Plus. your local declaration overrides the global declaration. FUNCTION TO_CHAR (left NUMBER. For instance. they operate independently of any timing mechanism). Package DBMS_SQL : allows PL/SQL to execute SQL data definition and data manipulation statements dynamically at run time. The package specification globally declares types. The alerts are transaction based and asynchronous (that is.Oracle PL/SQL Package STANDARD A package named STANDARD defines the PL/SQL environment. The put_line procedure outputs information to a buffer in the SGA. package STANDARD contains the following declarations: FUNCTION TO_CHAR (right DATE) RETURN VARCHAR2.. and subprograms. right VARCHAR2) RETURN VARCHAR2. FUNCTION TO_CHAR (left DATE. FUNCTION TO_CHAR (left NUMBER) RETURN VARCHAR2.

Oracle PL/SQL

Package DBMS_PIPE: allows different sessions to communicate over named pipes. (A pipe is an area of memory used by one process to pass information to another.) You can use the procedures pack_message and send_message to pack a message into a pipe, then send it to another session in the same instance. At the other end of the pipe, you can use the procedures receive_message and unpack_message to receive and unpack (read) the message. Named pipes are useful in many ways. For example, you can write routines in C that allow external servers to collect information, then send it through pipes to procedures stored in an Oracle database.

Package UTL_FILE: allows your PL/SQL programs to read and write operating system (OS) text files. It provides a restricted version of standard OS stream file I/O, including open, put, get, and close operations. When you want to read or write a text file, you call the function fopen, which returns a file handle for use in subsequent procedure calls. For example, the procedure put_line writes a text string and line terminator to an open file. The procedure get_line reads a line of text from an open file into an output buffer.

Package UTL_HTTP: allows your PL/SQL programs to make hypertext transfer protocol (HTTP) callouts. You can use it to retrieve data from the internet, or to call Oracle Web Server cartidges. The package has two entry points, each of which accepts a URL (universal resource locator) string, contacts the specified site, and returns the requested data, which is usually in hypertext markup language (HTML) format.

Advantages of Packages
Modularity : Packages let you encapsulate logically related types, objects, and subprograms in a named PL/SQL module. Each package is easy to understand, and the interfaces between packages are simple, clear, and well defined. Easier Application Design : When designing an application, you can code and compile a specification without its body. Once the specification has been compiled, stored subprograms that reference the package can be compiled as well. Information Hiding : With packages, you can specify which types, objects, and subprograms are public (visible and accessible) or private (hidden and inaccessible). For example, if a package contains four subprograms, three might be public and one private. The package hides the definition of the private subprogram so that only the package (not your application) is affected if the definition changes. This simplifies maintenance and enhancement. Also, by hiding implementation details from users, you protect the integrity of the package.

Jayashree

Page 58 of 69

Oracle PL/SQL

Added Functionality : Packaged public variables and cursors persist for the duration of a session. So, they can be shared by all subprograms that execute in the environment. Also, they allow you to maintain data across transactions without having to store it in the database. Better Performance : When you call a packaged subprogram for the first time, the whole package is loaded into memory. Therefore, subsequent calls to related subprograms in the package require no disk I/O.

Exercises
1. Create a function to return an employee’s bonus that is based on his salary and department to which he belongs. If he belongs to department 10 and is not a clerk or salesman, then he receives 4% bonus on his salary. If he belongs to department 10 and is a clerk or salesman, then he receives 5% bonus on his salary. All others receive 6% of salary as bonus. Test this function at the SQL*PLUS prompt using the command EXECUTE. 2. Create a procedure that accepts an argument n, and determines the top n employees with respect to salary. The procedure should display the ename and sal of these employees, as well as record the results in a table called TOP_SAL. Call this procedure from a PL/SQL block, or test it at the SQL*PLUS prompt using the command EXECUTE. 3. Create a PL/SQL block that calls a recursive function fact to compute and display the factorials of !..n numbers. 4. Create procedures for the following (refer to the ITEMMAST table): a) Item issue updation b) Item receipt updation c) Adding a new item Execute these procedures with the EXECUTE command.

Jayashree

Page 59 of 69

Oracle PL/SQL

Database Triggers
Topics
• • • • • Introduction to Triggers Creating a Database Trigger Triggers Examples INSTEAD OF Triggers Trigger Execution

Jayashree

Page 60 of 69

enforce complex security authorizations ..enforce referential integrity across nodes in a distributed database . Triggers can supplement the standard capabilities of Oracle to provide a highly customized database management system.prevent invalid transactions . a trigger can restrict DML operations against a table to those issued during regular business hours.. UPDATE. and that is implicitly executed when an INSERT.provide transparent event logging . ON table [REFERENCING {OLD [AS] old | NEW [AS] new}] [FOR EACH ROW] [WHEN (condition)] PL/SQL Block Jayashree Page 61 of 69 .gather statistics on table access • • Creating a Database Trigger CREATE [OR REPLACE] TRIGGER trigger-name [BEFORE | AFTER] {DELETE|INSERT|UPDATE [OF column [. A trigger could also restrict DML operations to occur only at certain times during weekdays. Other uses for triggers are to: . Oracle automatically executes a trigger when a specified SQL statement is issued against the table. column]…} [OR {DELETE|INSERT|UPDATE [OF column [.Oracle PL/SQL Introduction to Triggers • A database trigger is a stored PL/SQL procedure that is associated with a table.maintain synchronous table replicates . or DELETE statement is issued against the associated table. For example.provide sophisticated auditing .automatically generate derived column values .enforce complex business rules .column]…}].

The default correlation names are OLD and NEW. REFERENCING : specifies correlation names. before executing the triggering statement ORACLE fires the trigger only once. after executing the triggering statement AFTER Option Jayashree Page 62 of 69 . If this condition is satisfied.The definition of the triggering statement specifies what SQL statements cause Oracle to fire the trigger. updates or deletes With FOR EACH ROW option ORACLE fires the trigger before modifying each row affected by the triggering statement ORACLE fires the trigger after modifying each row affected by the triggering statement BEFORE Option ORACLE fires the trigger only once. you can use this clause to specify different correlation names to avoid confusion between the table name and the correlation name. then Oracle fires the trigger using the trigger action. The trigger restriction contains a SQL condition that must be satisfied for Oracle to fire the trigger. Trigger action : The trigger action specifies the PL/SQL block Oracle executes to fire the trigger. You can specify this condition with the WHEN clause. Trigger restriction : The trigger restriction specifies an additional condition that must be satisfied for a row trigger to be fired. You must also specify the table with which the trigger is associated.Oracle PL/SQL Parts of a Trigger • Triggering statement : DELETE. • • Oracle evaluates the condition of the trigger restriction whenever a triggering statement is issued. UPDATE . If your row trigger is associated with a table named OLD or NEW. The triggering statement is one that modifies this table. INSERT. You can use correlation names in the PL/SQL block and WHEN clause of a row trigger to refer specifically to old and new values of the current row. Types of Triggers Row-Level Triggers Statement-Level Triggers BEFORE and AFTER Triggers execute once for each row in a transaction execute once for each transaction executed immediately before or after inserts. WHEN : specifies the trigger restriction.

sal > maxsal) THEN raise_application_error( -20601.empno).sal || ' out of range for job ' || :new. BEGIN /* Get the minimum and maximum salaries for the employee's job from the SAL_GUIDE table. maxsal WHERE job = :new. details regarding the user.job <> 'PRESIDENT') DECLARE minsal maxsal NUMBER.job || ' for employee ' || :new. and the empno of the row deleted should be logged into another table del_history. 'Salary ' || :new. END IF. NUMBER. CREATE OR REPLACE TRIGGER del_check AFTER DELETE ON EMP FOR EACH ROW BEGIN INSERT INTO del_history VALUES (USER. END. while inserting a value for sal column or updating the sal column of an existing employee : CREATE TRIGGER salary_check BEFORE INSERT OR UPDATE OF sal.sal < minsal OR :new. To create a trigger for emp table to check the salary range.job. /* If the employee's salary is out of range */ /* then generate an error */ IF(:new. Jayashree Page 63 of 69 . job ON emp FOR EACH ROW WHEN (new.Oracle PL/SQL Triggers Examples 1. END. max_sal FROM sal_guide INTO minsal.ename ). :old. 2. */ SELECT min_sal. Whenever there is a deletion of row(s) from the emp table.

TO_CHAR(SYSDATE.ROWCNT. TO_CHAR(SYSDATE. Finally the statistical information is saved in the table STAT_TAB by the AFTER statement trigger. 5. A global session variable.Oracle PL/SQL 3. UPDATE. Suppose you have a table.ename). and you want to know when the table is being accessed and the types of queries being issued. DROP TABLE stat_tab. 4. ’HH:MI:SS’)). CREATE OR REPLACE TRIGGER upcase BEFORE INSERT OR UPDATE OF ename ON EMP FOR EACH ROW BEGIN :new. TO_CHAR(SYSDATE. CREATE TABLE stat_tab(utype CHAR(8). Jayashree Page 64 of 69 .ename := UPPER(:new. is initialized to zero by a BEFORE statement trigger. SAL. ELSIF DELETING THEN INSERT INTO opn_history VALUES (‘DELETE’. END IF. Ensure that the names of employees in the emp table are always in upper case. The example below contains a sample package and trigger that tracks this information by hour and type of action (for example. rowcnt INTEGER. CREATE OR REPLACE PACKAGE stat IS rowcnt INTEGER. END. STAT. CREATE OR REPLACE TRIGGER opn_check AFTER INSERT OR DELETE OR UPDATE ON EMP FOR EACH ROW BEGIN IF INSERTING THEN INSERT INTO opn_history VALUES (‘INSERT’. ELSIF UPDATING THEN INSERT INTO opn_history VALUES (‘UPDATE’. DELETE. Record all the types of operations done on the emp table along with the time. ’HH:MI:SS’)). ’HH:MI:SS’)). Then it is increased each time the row trigger is executed. END. END. or INSERT) on table SAL. uhour INTEGER).

END.TRUNC(SYSDATE)) * 24). EXCEPTION WHEN dup_val_on_index THEN UPDATE stat_tab SET rowcnt = rowcnt + stat. hour NUMBER. END. hour := TRUNC((SYSDATE . CREATE TRIGGER rt BEFORE UPDATE OR DELETE OR INSERT ON sal FOR EACH ROW BEGIN stat. stat. IF deleting THEN typ := 'delete'. BEGIN IF updating THEN typ := 'update'. END IF. Jayashree Page 65 of 69 .rowcnt + 1.rowcnt WHERE utype = typ AND uhour = hour.rowcnt WHERE utype = typ AND uhour = hour. END IF. END IF. CREATE TRIGGER at AFTER UPDATE OR DELETE OR INSERT ON sal DECLARE typ CHAR(8). UPDATE stat_tab SET rowcnt = rowcnt + stat.rowcnt.rowcnt := 0. IF SQL%ROWCOUNT = 0 THEN INSERT INTO stat_tab VALUES (typ. END. hour).rowcnt := stat. END IF. IF inserting THEN typ := 'insert'.Oracle PL/SQL CREATE TRIGGER bt BEFORE UPDATE OR DELETE OR INSERT ON sal BEGIN stat.

d. As a result of these ambiguities. INSTEAD OF triggers are activated for each row. d. p. • Inserting a row in a view could either mean inserting a new row into the base table or updating an existing row so that it will be projected by the view.deptno = p. Users write normal INSERT. Object views present additional problems. CREATE VIEW manager_info AS SELECT e. These triggers are called INSTEAD OF triggers because.mgr_no AND d. Example of an INSTEAD OF Trigger The following example shows an INSTEAD OF trigger for inserting rows into the MANAGER_INFO view. there are many restrictions on which views are modifiable.dept_type. a key use of object views is to represent master/detail relationships. e.name. An INSTEAD OF trigger can be used on object views as well as relational views that are not otherwise modifiable. DELETE. or delete operations directly on the underlying tables. and DELETE). and UPDATE statements against the view and the INSTEAD OF trigger works invisibly in the background to make the right actions take place.empno = d. dept d.projno FROM emp e. but modifying joins is inherently ambiguous. project p WHERE e. For example. p.level. Oracle fires the trigger instead of executing the triggering statement. The trigger performs update. UPDATE.empno. • Updating a column in a view that involves joins might change the semantics of other columns that are not projected by the view.Oracle PL/SQL INSTEAD OF Triggers • INSTEAD OF triggers provide a transparent way of modifying views that cannot be modified directly through SQL DML statements (INSERT. This inevitably involves joins. Jayashree Page 66 of 69 . By default. insert. unlike other types of triggers. • Modifying Views Modifying views has inherent problems of ambiguity.resp_dept. • Deleting a row in a view could either mean deleting it from the base table or updating some column values so that it will no longer be selected by the view.deptno.

empno = :n.project_level). :n. ELSE UPDATE dept SET dept.empno. Jayashree Page 67 of 69 .Oracle PL/SQL CREATE TRIGGER manager_info_insert INSTEAD OF INSERT ON manager_info REFERENCING NEW AS n -.level WHERE project.projno = :n. :n.new manager information FOR EACH ROW BEGIN IF NOT EXISTS SELECT * FROM emp WHERE emp. END IF.projno.deptno = :n.empno THEN INSERT INTO emp VALUES(:n.name).projno. IF NOT EXISTS SELECT * FROM project WHERE project.level = :n.deptno THEN INSERT INTO dept VALUES(:n. END IF.deptno = :n. END IF. IF NOT EXISTS SELECT * FROM dept WHERE dept.projno THEN INSERT INTO project VALUES(:n.name WHERE emp. ELSE UPDATE project SET project.dept_type).deptno.dept_type = :n.projno = :n.dept_type WHERE dept.deptno. ELSE UPDATE emp SET emp. END.empno = :n.empno.name = :n. :n.

Oracle PL/SQL Trigger Execution A trigger can be in either of two distinct modes: enabled An enabled trigger executes its trigger action if a triggering statement is issued and the trigger restriction (if any) evaluates to TRUE. For enabled triggers. Oracle automatically • executes triggers of each type in a planned firing sequence when more than one trigger is fired by a single SQL statement • performs integrity constraint checking at a set point in time with respect to the different types of triggers and guarantees that triggers cannot compromise integrity constraints • provides read-consistent views for queries and constraints • manages the dependencies among triggers and objects referenced in the code of the trigger action • uses two-phase commit if a trigger updates remote tables in a distributed database • fires multiple triggers in an unspecified order. if more than one trigger of the same type exists for a given statement Jayashree Page 68 of 69 . even if a triggering statement is issued and the trigger restriction (if any) would evaluate to TRUE. disabled A disabled trigger does not execute its trigger action.

then the trigger should fire for a confirmation. as newcomm = oldcomm * (newsal / oldsal). Create database triggers to (refer to the ITEMMAST table) : a) Check the QOH column value before any issue is made. in case the QOH goes below ROL for that item. c) Check the ROQ value in case of receipt of an item. Create a trigger to change the deptno in the EMP table whenever changes occur in the DEPT table. ‘OPERATIONS’).Oracle PL/SQL Exercises 1. 5. Jayashree Page 69 of 69 . ‘SUPPORT’). 6. Prevent users from modifying the EMP table at times other than between 8:30 am and 6:00 pm on week days. b) Store the necessary details in a table called RE_ORD. Consider the two tables: EMP EMPNO DEPTNO 1 10 2 10 3 30 4 20 5 20 DEPT DEPTNO 10 20 30 40 DNAME SALES RESEARCH OPERATIONS PRODUCTION Create a view emp_dept on these two tables. 3. If the receipt is more than the ROQ value. Write a database trigger to automatically update the commission of employees in the EMP table who are salesmen. and dname columns. 30. 2. ‘SUPPORT’). INSERT INTO emp_dept VALUES (7. INSERT INTO emp_dept VALUES (6. deptno. 50. 4. 30. Write an INSTEAD OF trigger for insert. which will allow you to execute the following commands successfully: INSERT INTO emp_dept VALUES (4. that selects empno. Create a trigger to make sure that the increase in salary for employees in the EMP table is only 10% of the previous salary.

Sign up to vote on this title
UsefulNot useful