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

An Introduction to PL/SQL

Team Rainbow & Wase

© Copyright Wipro Technologies


Objectives

 Distinguish between anonymous PL/SQL blocks and


named PL/SQL blocks (subprograms)

 Describe the PL/SQL development environments

Wipro Confidential 2
PL/SQL Program Constructs

Stored
Stored
Anonymous
Anonymous procedure/
procedure/
block
block
DECLARE function
function

BEGIN Application
Application
Application
Application procedure/
procedure/
trigger
trigger function
function
EXCEPTION

Database
END;
Database Package
trigger Package
trigger

Object
Object type
type

Wipro Confidential 3
Block Structure for Anonymous PL/SQL Blocks

DECLARE (optional)
Declare PL/SQL objects to be used within this block
BEGIN (mandatory)
Define the executable statements
EXCEPTION (optional)
Define the actions that take place if an error arises
END; (mandatory)

Wipro Confidential 4
Block Structure for PL/SQL Subprograms

Header
IS
Declaration section
BEGIN
Executable section
EXCEPTION (optional)
Exception section
END;

Wipro Confidential 5
Benefits of Subprograms

 Improved maintenance

 Improved data security and integrity

 Improved performance

Wipro Confidential 6
Developing Procedures and Functions Using SQL*Plus

Wipro Confidential 7
Writing Control Structures

Wipro Confidential 8
Objectives

 After completing this lesson, you should be able to do


the following:

 Identify the uses and types of control structures


 Construct an IF statement
 Construct and identify different loop statements
 Use logic tables
 Control block flow using nested loops and labels

Wipro Confidential 9
Controlling PL/SQL Flow of Execution

 You can change the logical flow of statements using


conditional IF statements and loop control structures.

 Conditional IF statements:
 IF-THEN-END IF
 IF-THEN-ELSE-END IF
 IF-THEN-ELSIF-END IF

Wipro Confidential 10
IF Statements

Syntax
IF
IF condition
condition THEN
THEN
statements;
statements;
[ELSIF
[ELSIF condition
condition THEN
THEN
statements;]
statements;]
[ELSE
[ELSE
statements;]
statements;]
END
END IF;
IF;

Simple IF Statement:
Set the manager ID to 22 if the employee name is Osborne.
IF
IF v_ename
v_ename == 'OSBORNE'
'OSBORNE' THEN
THEN
v_mgr
v_mgr :=
:= 22;
22;
END
END IF;
IF;

Wipro Confidential 11
Simple IF Statements

Set the job title to Salesman, the department number to 35, and
the commission to 20%of the current salary if the last name is
Miller.

Example
.. .. ..
IF
IF v_ename
v_ename == 'MILLER'
'MILLER' THEN
THEN
v_job
v_job :=
:= 'SALESMAN';
'SALESMAN';
v_deptno
v_deptno :=
:= 35;
35;
v_new_comm
v_new_comm :=
:= sal
sal ** 0.20;
0.20;
END
END IF;
IF;
.. .. ..

Wipro Confidential 12
IF-THEN-ELSE Statement Execution Flow

TRUE FALSE
IF Condition

THEN
THEN Actions
Actions ELSE
ELSE actions
actions
(including
(including further
further IFs)
IFs) (including
(including further
further IFs)
IFs)

Wipro Confidential 13
IF-THEN-ELSE Statements

Set a flag for orders where there are fewer than 5 days between
order date and ship date.

Example
...
...
IF
IF v_shipdate
v_shipdate -- v_orderdate
v_orderdate << 55 THEN
THEN
v_ship_flag
v_ship_flag :=
:= 'Acceptable';
'Acceptable';
ELSE
ELSE
v_ship_flag
v_ship_flag :=
:= 'Unacceptable';
'Unacceptable';
END
END IF;
IF;
...
...

Wipro Confidential 14
IF-THEN-ELSIF Statement Execution Flow

IF
IF Condition
Condition
TRUE FALSE

ELSIF
ELSIF
Condition
Condition
THEN
THEN Actions
Actions
TRUE FALSE

ELSE
ELSE
THEN
THEN Actions
Actions Actions
Actions

Wipro Confidential 15
IF-THEN-ELSIF Statements

For a given value entered, return a calculated value.

Example
.. .. ..
IF
IF v_start
v_start >> 100
100 THEN
THEN
v_start
v_start :=
:= 22 ** v_start;
v_start;
ELSIF
ELSIF v_start
v_start >=
>= 50
50 THEN
THEN
v_start
v_start :=
:= .5
.5 ** v_start;
v_start;
ELSE
ELSE
v_start
v_start :=
:= .1
.1 ** v_start;
v_start;
END
END IF;
IF;
.. .. ..

Wipro Confidential 16
Building Logical Conditions

 You can handle null values with the IS NULL operator.

 Any expression containing a null value evaluates to


NULL.

 Concatenated expressions with null values treat null


values as an empty string.

Wipro Confidential 17
Logic Tables

Build a simple Boolean condition with a comparison operator.

AND TRUE FALSE NULL OR TRUE FALSE NULL NOT

TRUE TRUE FALSE NULL TRUE TRUE TRUE TRUE TRUE FALSE

FALSE FALSE FALSE FALSE FALSE TRUE FALSE NULL FALSE TRUE

NULL NULL FALSE NULL NULL TRUE NULL NULL NULL NULL

Wipro Confidential 18
Boolean Conditions

What is the value of V_FLAG in each case?

v_flag
v_flag :=
:= v_reorder_flag
v_reorder_flag AND
AND v_available_flag;
v_available_flag;

V_REORDER_FLAG V_AVAILABLE_FLAG V_FLAG


TRUE TRUE TRUE
TRUE FALSE FALSE
NULL TRUE NULL
NULL FALSE FALSE

Wipro Confidential 19
Iterative Control: LOOP Statements

 Loops repeat a statement or sequence of statements


multiple times.

 There are three loop types:


 Basic loop
 FOR loop
 WHILE loop

Wipro Confidential 20
Basic Loop

Syntax

LOOP
LOOP -- delimiter
statement1;
statement1; -- statements
.. .. ..
EXIT -- EXIT statement
EXIT [WHEN
[WHEN condition];
condition];
END
END LOOP;
LOOP; -- delimiter

where:
where: condition
condition is
is aa Boolean
Boolean variable
variable or
or
expression
expression (TRUE,
(TRUE, FALSE,
FALSE,
or
or NULL);
NULL);

Wipro Confidential 21
Basic Loop

Example

DECLARE
DECLARE
v_ordid
v_ordid item.ordid%TYPE
item.ordid%TYPE :=:= 101;
101;
v_counter
v_counter NUMBER(2)
NUMBER(2) :=
:= 1;
1;
BEGIN
BEGIN
LOOP
LOOP
INSERT
INSERT INTO
INTO item(ordid,
item(ordid, itemid)
itemid)
VALUES(v_ordid,
VALUES(v_ordid, v_counter);
v_counter);
v_counter
v_counter :=
:= v_counter
v_counter ++ 1;
1;
EXIT
EXIT WHEN
WHEN v_counter
v_counter >> 10;
10;
END
END LOOP;
LOOP;
END;
END;

Wipro Confidential 22
FOR Loop

Syntax
FOR
FOR counter
counter in
in [REVERSE]
[REVERSE]
lower_bound..upper_bound
lower_bound..upper_bound LOOP
LOOP
statement1;
statement1;
statement2;
statement2;
.. .. ..
END
END LOOP;
LOOP;

Use a FOR loop to shortcut the test for the number of iterations.
Do not declare the index; it is declared implicitly.

Wipro Confidential 23
FOR Loop

 Guidelines

 Reference the counter within the loop only; it is


undefined outside the loop.
 Use an expression to reference the existing value of a
counter.
 Do not reference the counter as the target of an
assignment.

Wipro Confidential 24
FOR Loop

 Insert the first 10 new line items for order number 101.

Example

DECLARE
DECLARE
v_ordid
v_ordid item.ordid%TYPE
item.ordid%TYPE :=
:= 101;
101;
BEGIN
BEGIN
FOR
FOR ii IN
IN 1..10
1..10 LOOP
LOOP
INSERT
INSERT INTO
INTO item(ordid,
item(ordid, itemid)
itemid)
VALUES(v_ordid,
VALUES(v_ordid, i);
i);
END
END LOOP;
LOOP;
END;
END;

Wipro Confidential 25
WHILE Loop

Syntax

WHILE
WHILE condition
condition LOOP
LOOP Condition is
statement1;
statement1; evaluated at the
statement2;
statement2; beginning of
.. .. .. each iteration.
END
END LOOP;
LOOP;

Use the WHILE loop to repeat statements while a condition is TRUE.

Wipro Confidential 26
WHILE Loop

Example

ACCEPT
ACCEPT p_price
p_price PROMPT
PROMPT 'Enter
'Enter the
the price
price ofof the
the item:
item: ''
ACCEPT
ACCEPT p_itemtot
p_itemtot PROMPT
PROMPT 'Enter
'Enter the
the maximum
maximum total
total for
for
purchase
purchase of
of item:
item: ''
DECLARE
DECLARE
...
...
v_qty
v_qty NUMBER(8)
NUMBER(8) :=:= 1;
1;
v_running_total
v_running_total NUMBER(7,2)
NUMBER(7,2) :=:= 0;
0;
BEGIN
BEGIN
...
...
WHILE
WHILE v_running_total
v_running_total << &p_itemtot
&p_itemtot LOOP
LOOP
...
...
v_qty
v_qty :=
:= v_qty
v_qty ++ 1;
1;
v_running_total
v_running_total :=:= v_qty
v_qty ** &p_price;
&p_price;
END
END LOOP;
LOOP;
...
...

Wipro Confidential 27
Nested Loops and Labels

 Nest loops to multiple levels.

 Use labels to distinguish between blocks and loops.

 Exit the outer loop with the EXIT statement referencing


the label.

Wipro Confidential 28
Nested Loops and Labels

...
...
BEGIN
BEGIN
<<Outer_loop>>
<<Outer_loop>>
LOOP
LOOP
v_counter
v_counter :=
:= v_counter+1;
v_counter+1;
EXIT
EXIT WHEN
WHEN v_counter>10;
v_counter>10;
<<Inner_loop>>
<<Inner_loop>>
LOOP
LOOP
...
...
EXIT
EXIT Outer_loop
Outer_loop WHEN
WHEN total_done
total_done == 'YES';
'YES';
--
-- Leave
Leave both
both loops
loops
EXIT
EXIT WHEN
WHEN inner_done
inner_done == 'YES';
'YES';
--
-- Leave
Leave inner
inner loop
loop only
only
...
...
END
END LOOP
LOOP Inner_loop;
Inner_loop;
...
...
END
END LOOP
LOOP Outer_loop;
Outer_loop;
END;
END;

Wipro Confidential 29
Summary

 Change the logical flow of statements by using control


structures.

 Conditional (IF statement)

 Loops
 Basic loop
 FOR loop
 WHILE loop
 EXIT statement

Wipro Confidential 30
Writing Explicit Cursors

Wipro Confidential 31
Objectives

 After completing this lesson, you should be able to do


the following:

 Distinguish between an implicit and an explicit cursor


 Use a PL/SQL record variable
 Write a Cursor FOR loop

Wipro Confidential 32
About Cursors

 Every SQL statement executed by the Oracle Server has


an individual cursor associated with it:

 Implicit cursors: Declared for all DML and PL/SQL


SELECT statements.
 Explicit cursors: Declared and named by the
programmer.

Wipro Confidential 33
Explicit Cursor Functions

Result Set

7369 SMITH CLERK


7566 JONES MANAGER
Cursor 7788 SCOTT ANALYST Current Row
7876 ADAMS CLERK
7902 FORD ANALYST

Wipro Confidential 34
Controlling Explicit Cursors

No

Yes
DECLARE
DECLARE OPEN
OPEN FETCH
FETCH EMPTY? CLOSE
CLOSE

 Create a  Identify  Load the  Test for  Release


named the active current existing the active
SQL area set row into rows set
variables  Return to
FETCH if
rows
found

Wipro Confidential 35
Controlling Explicit Cursors

Open the cursor.


Pointer

Cursor
Fetch a Row from the cursor.

Pointer
Cursor
Continue until empty.

Pointer

Cursor
Close the cursor.

Cursor

Wipro Confidential 36
Declaring the Cursor

Syntax

CURSOR
CURSOR cursor_name
cursor_name IS
IS
select_statement;
select_statement;

 Do not include the INTO clause in the cursor declaration.


 If processing rows in a specific sequence is required use
the ORDER BY clause in the query.

Wipro Confidential 37
Declaring the Cursor

Example
DECLARE
DECLARE
CURSOR
CURSOR c1
c1 IS
IS
SELECT
SELECT empno,
empno, ename
ename
FROM
FROM emp;
emp;

CURSOR
CURSOR c2
c2 IS
IS
SELECT
SELECT **
FROM
FROM dept
dept
WHERE
WHERE deptno
deptno == 10;
10;
BEGIN
BEGIN
...
...

Wipro Confidential 38
Opening the Cursor

Syntax

OPEN
OPEN cursor_name;
cursor_name;

 Open the cursor to execute the query and identify the


active set.
 If the query returns no rows, no exception is raised.
 Use cursor attributes to test the outcome after a fetch.

Wipro Confidential 39
Fetching Data from the Cursor

Syntax

FETCH
FETCH cursor_name
cursor_name INTO
INTO [variable1,
[variable1, variable2,
variable2, ...]
...]
|| record_name];
record_name];

 Retrieve the current row values into output variables.


 Include the same number of variables.
 Match each variable to correspond to the columns
positionally.
 Test to see if the cursor contains rows.

Wipro Confidential 40
Fetching Data from the Cursor

Examples

FETCH
FETCH c1
c1 INTO
INTO v_empno,
v_empno, v_ename;
v_ename;

...
...
OPEN
OPEN defined_cursor;
defined_cursor;
LOOP
LOOP
FETCH
FETCH defined_cursor
defined_cursor INTO
INTO defined_variables
defined_variables
EXIT
EXIT WHEN
WHEN ...;
...;
...
...
--
-- Process
Process the
the retrieved
retrieved data
data
...
...
END;
END;

Wipro Confidential 41
Closing the Cursor

Syntax
CLOSE
CLOSE cursor_name;
cursor_name;

 Close the cursor after completing the processing of the


rows.
 Reopen the cursor, if required.
 Do not attempt to fetch data from a cursor once it has
been closed.

Wipro Confidential 42
Explicit Cursor Attributes

Obtain status information about a cursor.

Attribute Type Description


%ISOPEN Boolean Evaluates to TRUE if the cursor
is open
%NOTFOUND Boolean Evaluates to TRUE if the most
recent fetch does not return a
row
%FOUND Boolean Evaluates to TRUE if the most
recent fetch returns a row;
complement of %NOTFOUND
%ROWCOUNT Number Evaluates to the total number of
rows returned so far

Wipro Confidential 43
Controlling Multiple Fetches

 Process several rows from an explicit cursor using a


loop.
 Fetch a row with each iteration.
 Use the %NOTFOUND attribute to write a test for an
unsuccessful fetch.
 Use explicit cursor attributes to test the success of each
fetch.

Wipro Confidential 44
The %ISOPEN Attribute

 Fetch rows only when the cursor is open.


 Use the %ISOPEN cursor attribute before performing a
fetch to test whether the cursor is open.

Example

IF
IF NOT
NOT c1%ISOPEN
c1%ISOPEN THEN
THEN
OPEN
OPEN c1;
c1;
END
END IF;
IF;
LOOP
LOOP
FETCH
FETCH c1...
c1...

Wipro Confidential 45
The %NOTFOUND and %ROWCOUNT Attributes

 Use the %ROWCOUNT cursor attribute to retrieve an exact


number of rows.
 Use the %NOTFOUND cursor attribute to determine when to
exit the loop.

Wipro Confidential 46
Cursors and Records

Process the rows of the active set conveniently by fetching


values into a PL/SQL RECORD.

Example
...
...
CURSOR
CURSOR c1
c1 IS
IS
SELECT
SELECT empno,
empno, ename
ename
FROM
FROM emp;
emp;
emp_record
emp_record c1%ROWTYPE;
c1%ROWTYPE;
BEGIN
BEGIN
OPEN
OPEN c1;
c1;
.. .. ..
FETCH
FETCH c1
c1 INTO
INTO emp_record;
emp_record;

Wipro Confidential 47
Cursor FOR Loops

Syntax

FOR
FOR record_name
record_name IN
IN cursor_name
cursor_name LOOP
LOOP
statement1;
statement1;
statement2;
statement2;
.. .. ..
END
END LOOP;
LOOP;

 Shortcut to process explicit cursors.


 Implicit open, fetch, and close occur.
 Do not declare the record; it is implicitly declared.

Wipro Confidential 48
Cursor FOR Loops

Retrieve employees one by one until there are no more left.

Example
DECLARE
DECLARE
CURSOR
CURSOR c1 c1 IS
IS
SELECT
SELECT empno,
empno, ename
ename
FROM
FROM emp;
emp;
BEGIN
BEGIN
FOR
FOR emp_record
emp_record ININ c1
c1 LOOP
LOOP
--
-- implicit open and
implicit open and implicit
implicit fetch
fetch occur
occur
IF
IF emp_record.empno
emp_record.empno == 7839
7839 THEN
THEN
...
...
END
END LOOP;
LOOP; --
-- implicit
implicit close
close occurs
occurs
END;
END;

Wipro Confidential 49
Cursor FOR Loops Using Subqueries

 No Need to declare the cursor.


 Example

BEGIN
BEGIN
FOR
FOR emp_record
emp_record IN
IN (( SELECT
SELECT empno,
empno, ename
ename
FROM
FROM emp)
emp) LOOP
LOOP
--
-- implicit
implicit open
open and
and implicit
implicit fetch
fetch occur
occur
IF
IF emp_record.empno
emp_record.empno == 7839
7839 THEN
THEN
...
...
END
END LOOP; --
LOOP; -- implicit
implicit close
close occurs
occurs
END;
END;

Wipro Confidential 50
Cursors - Using For Loops

declare
cursor c_emp is
select ename,sal,comm from emp;
total number;
begin
for emp_rec in c_emp loop
total := emp_rec.sal + emp_rec.comm;
dbms_output.put_line(c_emp%rowcount||' '||total);
exit when c_emp%notfound;
end loop;
end;

Wipro Confidential 51
Summary

 Cursor types:

 Implicit cursors: Used for all DML statements and


single-row queries.
 Explicit cursors: Used for queries of zero, one, or
more rows.
 Manipulate explicit cursors.

 Evaluate the cursor status by using cursor attributes.

 Use cursor FOR loops.

Wipro Confidential 52
Advanced Explicit Cursor Concepts

Wipro Confidential 53
Objectives

 After completing this lesson, you should be able to do the


following:
 Write a cursor that uses parameters

 Determine when a FOR UPDATE clause in a cursor is


required
 Determine when to use the WHERE CURRENT OF clause

 Write a cursor that uses a subquery

Wipro Confidential 54
Cursors with Parameters

Syntax

CURSOR
CURSOR cursor_name
cursor_name
[(parameter_name
[(parameter_name datatype,
datatype, ...)]
...)]
IS
IS
select_statement;
select_statement;

 Pass parameter values to a cursor when the cursor is


opened and the query is executed.
 Open an explicit cursor several times with a different
active set each time.

Wipro Confidential 55
Cursors with Parameters

 Pass the department number and job title to the WHERE clause.
 Example

DECLARE
DECLARE
CURSOR
CURSOR c1
c1
(v_deptno
(v_deptno NUMBER,
NUMBER, v_job
v_job VARCHAR2)
VARCHAR2) IS
IS
SELECT
SELECT empno,
empno, ename
ename
FROM
FROM emp
emp
WHERE
WHERE deptno
deptno == v_deptno
v_deptno
AND
AND job
job == v_job;
v_job;
BEGIN
BEGIN
OPEN
OPEN c1(10,
c1(10, 'CLERK');
'CLERK');
...
...

Wipro Confidential 56
The FOR UPDATE Clause

Syntax
SELECT
SELECT ...
...
FROM
FROM ...
...
FOR
FOR UPDATE
UPDATE [OF
[OF column_reference][NOWAIT]
column_reference][NOWAIT]

 Explicit locking lets you deny access for the duration of a


transaction.
 Lock the rows before the update or delete.

Wipro Confidential 57
Examples - ‘ FOR UPDATE ‘

SQL> SELECT * FROM emp1 FOR UPDATE;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


……………………………………………………………………………..
7839 KING …….
7698 BLAKE …..

SQL> UPDATE emp1 SET sal = 1000;


14 rows updated
SQL> GRANT ALL ON emp1 TO username;

Wipro Confidential 58
Examples - ‘ FOR UPDATE ‘

SQL> CONNECT username / password

SQL>SELECT * FROM username.EMP1;

SQL> UPDATE emp1 SET sal = 1000;


|

Wipro Confidential 59
Examples - ‘ FOR UPDATE ‘

SQL> SHOW USER


USER is “VIMAL”

SQL>COMMIT;
commit complete.

Wipro Confidential 60
Examples - ‘ FOR UPDATE ‘

SQL> CONNECT username / password

SQL>SELECT * FROM username.EMP1;

SQL> UPDATE emp1 SET sal = 1000;

14 rows updated.
SQL>

Wipro Confidential 61
Examples - ‘ FOR UPDATE - NOWAIT ‘

SQL> SELECT * FROM emp1 FOR UPDATE NOWAIT;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


……………………………………………………………………………..
7839 KING …….
7698 BLAKE …..

SQL> UPDATE emp1 SET sal = 1000;


14 rows updated
SQL>

Wipro Confidential 62
Examples - ‘ FOR UPDATE - NOWAIT ‘

SQL> CONNECT username / password


SQL>SELECT * FROM username.EMP1 FOR UPDATE
2 NOWAIT;
….
14 rows selected.

SQL> UPDATE emp1 SET sal = 1000;

ERROR at line 1:
ORA-00054: resource busy and acquire with NOWAIT specified

Wipro Confidential 63
The FOR UPDATE Clause

 Retrieve the orders for amounts over $1000 that were


processed today.
 Example

DECLARE
DECLARE
CURSOR
CURSOR c1
c1 IS
IS
SELECT
SELECT empno,
empno, ename
ename
FROM
FROM emp
emp
FOR
FOR UPDATE
UPDATE NOWAIT;
NOWAIT;

Wipro Confidential 64
The WHERE CURRENT OF Clause

Syntax
WHERE
WHERE CURRENT
CURRENT OF
OF cursor
cursor

 Use cursors to update or delete the current row.


 Include the FOR UPDATE clause in the cursor
query to lock the rows first.
 Use the WHERE CURRENT OF clause to
reference the current row from an explicit cursor.

Wipro Confidential 65
The WHERE CURRENT OF Clause

Example

DECLARE
CURSOR c1 IS
SELECT ...
FOR UPDATE NOWAIT;
BEGIN
...
FOR emp_record IN c1 LOOP
UPDATE ...
WHERE CURRENT OF c1;
...
END LOOP;
COMMIT;
END;

Wipro Confidential 66
EXAMPLES - ‘ FOR UPDATE ‘ and ‘ WHERE CURRENT OF ‘
CLAUSE

create or replace procedure p_c


is
cursor c_emp1 is
select sal,comm from emp1;
total number;
begin
for emp1_rec in c_emp1 loop
update emp1 set sal = 1 where current of c_emp1;
dbms_output.put_line('1 ROW UPDATED');
end loop;
end;

Wipro Confidential 67
EXAMPLES - ‘ FOR UPDATE ‘ and ‘ WHERE CURRENT OF ‘
CLAUSE

create or replace procedure p_c


is
cursor c_emp1 is
select sal,comm from emp1 for update;
total number;
begin
for emp1_rec in c_emp1 loop
update emp1 set sal = 1 where current of c_emp1;
dbms_output.put_line('1 ROW UPDATED');
end loop;
end;

Wipro Confidential 68
Cursors with Subqueries

Example
DECLARE
DECLARE
CURSOR
CURSOR my_cursor
my_cursor IS
IS
SELECT
SELECT t1.deptno,
t1.deptno, dname,
dname, STAFF
STAFF
FROM
FROM dept
dept t1,
t1, (SELECT
(SELECT deptno,
deptno,
count(*)
count(*) STAFF
STAFF
FROM
FROM emp
emp
GROUP
GROUP BY
BY deptno)
deptno) t2
t2
WHERE
WHERE t1.deptno
t1.deptno == t2.deptno
t2.deptno
AND
AND STAFF
STAFF >=
>= 5;
5;

Wipro Confidential 69
Summary

 Return different results sets using cursors with


parameters.
 Define cursors with subqueries and correlated
subqueries.
 Manipulate explicit cursors with commands:
 FOR UPDATE Clause
 WHERE CURRENT OF Clause

Wipro Confidential 70
Handling Exceptions

Wipro Confidential 71
Objectives

 After completing this lesson, you should be able to do


the following:
 Define PL/SQL exceptions
 Recognize unhandled exceptions
 List and use different types of PL/SQL exception
handlers
 Trap unanticipated errors
 Describe the effect of exception propagation in nested
blocks
 Customize PL/SQL exception messages

Wipro Confidential 72
Handling Exceptions with PL/SQL

 What is an exception?
 Identifier in PL/SQL that is raised during execution.
 How is it raised?
 An Oracle error occurs.
 You raise it explicitly.
 How do you handle it?
 Trap it with a handler.
 Propagate it to the calling environment.

Wipro Confidential 73
Handling Exceptions

Trap the Propagate the Exception


Exception
DECLARE DECLARE

BEGIN BEGIN
Exception Exception
is raised is raised
EXCEPTION EXCEPTION

Exception Exception is
is trapped END; END; not trapped

Exception
propagates to calling
environment

Wipro Confidential 74
Exception Types

 Predefined Oracle Server

 Non-predefined Oracle Server


} Implicitly
raised

 User-defined Explicitly raised

Wipro Confidential 75
Trapping Exceptions

Syntax

EXCEPTION
EXCEPTION
WHEN
WHEN exception1
exception1 [OR
[OR exception2
exception2 .. .. .]
.] THEN
THEN
statement1;
statement1;
statement2;
statement2;
.. .. ..
[WHEN
[WHEN exception3
exception3 [OR
[OR exception4
exception4 .. .. .]
.] THEN
THEN
statement1;
statement1;
statement2;
statement2;
.. .. .]
.]
[WHEN
[WHEN OTHERS
OTHERS THEN
THEN
statement1;
statement1;
statement2;
statement2;
.. .. .]
.]

Wipro Confidential 76
Trapping Exceptions Guidelines

 WHEN OTHERS is the last clause.

 EXCEPTION keyword starts exception-handling section.

 Several exception handlers are allowed.

 Only one handler is processed before leaving the block.

Wipro Confidential 77
Trapping Predefined Oracle Server Errors

 Reference the standard name in the exception-handling


routine.
 Sample predefined exceptions:
 NO_DATA_FOUND
 TOO_MANY_ROWS
 INVALID_CURSOR
 ZERO_DIVIDE
 DUP_VAL_ON_INDEX

Wipro Confidential 78
Predefined Exception

Syntax
BEGIN SELECT ... COMMIT;
EXCEPTION
WHEN NO_DATA_FOUND THEN
statement1;
statement2;

WHEN TOO_MANY_ROWS THEN


statement1;
WHEN OTHERS THEN
statement1;
statement2;
statement3;
END;

Wipro Confidential 79
When ‘no_data_found’- Examples

DECLARE
a number;
BEGIN
select sal into a from emp where deptno = 11;
dbms_output.put_line(a);
EXCEPTION
when no_data_found then
dbms_output.put_line('there is no department ‘);
END;

Wipro Confidential 80
When ‘to_many_rows’- Examples

DECLARE
a number;
BEGIN
select sal into a from emp;
dbms_output.put_line(a);
EXCEPTION
when too_many_rows then
dbms_output.put_line(’To Many Rows Selected');
END;

Wipro Confidential 81
When ‘zero_divide’- Examples

DECLARE
a number;
b number;
c number := 0;
BEGIN
select deptno into a from dept where deptno = 10;
b := a/c;
dbms_output.put_line(c);
EXCEPTION
when zero_divide then
dbms_output.put_line('Do Not Divide By Zero');
END;

Wipro Confidential 82
Trapping Non-Predefined Oracle Server Errors

Declare Associate Reference

Declarative Section Exception-Handling


Section

 Name the  Code the PRAGMA  Handle the


exception EXCEPTION_INIT raised
exception

Wipro Confidential 83
Non-Predefined Error

Trap for Oracle Server error number -2292 an integrity constraint


violation

DECLARE
DECLARE
e_products_invalid
e_products_invalid EXCEPTION;
EXCEPTION; 1
e_products_invalid EXCEPTION;
PRAGMA
PRAGMA EXCEPTION_INIT
PRAGMA EXCEPTION_INIT
EXCEPTION_INIT (((
e_products_invalid, 2
e_products_invalid, -2292);
-2292);
v_message
v_message VARCHAR2(50);
VARCHAR2(50);
BEGIN
BEGIN
.. .. ..
EXCEPTION
EXCEPTION
WHEN e_products_invalid
WHEN e_products_invalid THEN
THEN 3
:g_message
:g_message :=
:= 'Product
'Product code
code
specified
specified is
is not
not valid.';
valid.';
.. .. ..
END;
END;

Wipro Confidential 84
Trapping Oracle Server Errors

DECLARE
a number;
b number;
c number := 0;
z_d exception;
pragma exception_init(z_d,-1476);
BEGIN
select deptno into a from dept where deptno = 10;
b := a/c;
dbms_output.put_line(c);
EXCEPTION
when z_d then
dbms_output.put_line('Do Not Divide By Zero');
END;

Wipro Confidential 85
Trapping User-Defined Exceptions

Declare Raise Reference

Declarative Executable Exception-Handling


Section Section Section

 Name the  Explicitly raise the  Handle the


exception exception by using raised
the RAISE statement exception

Wipro Confidential 86
User-Defined Exception

Example
[DECLARE]
[DECLARE]
e_amount_remaining
e_amount_remaining
e_amount_remaining EXCEPTION;
EXCEPTION;
EXCEPTION; 1
.. .. ..
BEGIN
BEGIN
.. .. ..
RAISE
RAISEe_amount_remaining;
RAISE e_amount_remaining;
e_amount_remaining;
.. .. .. 2
EXCEPTION
EXCEPTION
WHEN e_amount_remaining
WHEN e_amount_remaining
e_amount_remaining THEN
THEN
:g_message
:g_message :=
:= 'There
'There is
is still
still an
an amount
amount 3
in
in stock.';
stock.';
.. .. ..
END;
END;

Wipro Confidential 87
Examples - User Defined Exceptions

DECLARE
a number;
b number;
c number := 0;
z_d exception;
BEGIN
select deptno into a from dept where deptno = 10;
if c = 0 then raise z_d;
else b := a/c;
end if;
dbms_output.put_line(c);
EXCEPTION
when z_d then
dbms_output.put_line('Do Not Divide By Zero');
END;

Wipro Confidential 88
Functions for Trapping Exceptions

 SQLCODE
 Returns the numeric value for the error code
 SQLERRM
 Returns the message associated with the error
number

Wipro Confidential 89
Examples - SQLERRM

CREATE OR REPLACE PROCEDURE sql_err


IS
a NUMBER;
b VARCHAR2(255);
BEGIN
FOR i IN 0..20 LOOP
b := SQLERRM(-i);
DBMS_OUTPUT.PUT_LINE(b);
END LOOP;
END;

Wipro Confidential 90
Examples - SQLCODE

DECLARE
my_sqlcode NUMBER;
BEGIN
...
EXCEPTION
WHEN OTHERS THEN
my_sqlcode := SQLCODE;
INSERT INTO errors VALUES (my_sqlcode, ...);
END;

Wipro Confidential 91
Functions for Trapping Exceptions

Example

DECLARE
v_error_code NUMBER;
v_error_message VARCHAR2(255);
BEGIN
...
EXCEPTION
...
WHEN OTHERS THEN
ROLLBACK;
v_error_code := SQLCODE ;
v_error_message := SQLERRM ;
INSERT INTO errors VALUES(v_error_code,
v_error_message);
END;

Wipro Confidential 92
Propagating Exceptions

DECLARE
. . .
e_no_rows exception;
e_integrity exception;
PRAGMA EXCEPTION_INIT (e_integrity, -2292);
BEGIN
FOR c_record IN emp_cursor LOOP
BEGIN
SELECT ...
Sub-blocks can handle UPDATE ...
IF SQL%NOTFOUND THEN
an exception or pass RAISE e_no_rows;
the exception to the END IF;
EXCEPTION
enclosing block. WHEN e_integrity THEN ...
WHEN e_no_rows THEN ...
END;
END LOOP;
EXCEPTION
WHEN NO_DATA_FOUND THEN . . .
WHEN TOO_MANY_ROWS THEN . . .
END;

Wipro Confidential 93
RAISE_APPLICATION_ERROR

Syntax
raise_application_error
raise_application_error (error_number,
(error_number,
message[,
message[, {TRUE
{TRUE || FALSE}]);
FALSE}]);

 A procedure that lets you issue user-defined error


messages from stored subprograms.
 Called only from an executing stored subprogram.

Wipro Confidential 94
RAISE_APPLICATION_ERROR

 Used in two different places:


 Executable section
 Exception section

 Returns error conditions to the user in a manner


consistent with other Oracle Server errors

Wipro Confidential 95
Summary

 Exception types:
 Predefined Oracle Server error
 Non-predefined Oracle Server error
 User-defined error
 Trap exceptions
 Handle exceptions:
 Trap the exception within the PL/SQL block
 Propagate the exception

Wipro Confidential 96
Creating Functions

Wipro Confidential
Working with Composite Data types

Wipro Confidential 98
Objectives

 After completing this lesson, you should be able to do


the following:
 Create user-defined PL/SQL records
 Create a record with the %ROWTYPE attribute
 Create a PL/SQL table
 Create a PL/SQL table of records
 Describe the difference between records, tables, and
tables of records

Wipro Confidential 99
Composite Datatypes

 Types:
 PL/SQL RECORDS
 PL/SQL TABLES
 Contain internal components
 Are reusable

Wipro Confidential 100


PL/SQL Records

 Must contain one or more components of any scalar,


RECORD, or PL/SQL TABLE datatype-called fields
 Are similar in structure to records in a 3GL

 Are not the same as rows in a database table

 Treat a collection of fields as a logical unit

 Are convenient for fetching a row of data from a table


for processing

Wipro Confidential 101


Creating a PL/SQL Record

Syntax
TYPE
TYPE type_name
type_name IS
IS RECORD
RECORD
(field_declaration[,
(field_declaration[, field_declaration]…);
field_declaration]…);
identifier
identifier type_name;
type_name;

Where field_declaration stands for


field_name
field_name {field_type
{field_type || variable%TYPE
variable%TYPE
|| table.column%TYPE
table.column%TYPE || table%ROWTYPE}
table%ROWTYPE}
[[NOT
[[NOT NULL]
NULL] {:=
{:= || DEFAULT}
DEFAULT} expr]
expr]

Wipro Confidential 102


Creating a PL/SQL Record

 Declare variables to store the name, job, and salary of a new


employee.

Example
...
...
TYPE
TYPE emp_record_type
emp_record_type IS
IS RECORD
RECORD
(ename
(ename VARCHAR2(10),
VARCHAR2(10),
job
job VARCHAR2(9),
VARCHAR2(9),
sal
sal NUMBER(7,2));
NUMBER(7,2));
emp_record
emp_record emp_record_type;
emp_record_type;
...
...

Wipro Confidential 103


PL/SQL Record Structure

Field1 (datatype) Field2 (datatype) Field3 (datatype)

Example

Field1 (datatype) Field2 (datatype) Field3 (datatype)


empno number(4) ename varchar2(10) job varchar2(9)

Wipro Confidential 104


The %ROWTYPE Attribute

 Declare a variable according to a collection of columns


in a database table or view.
 Prefix %ROWTYPE with the database table.
 Fields in the record take their names and datatypes from
the columns of the table or view.

Wipro Confidential 105


Advantages of Using %ROWTYPE

 The number and datatypes of the underlying database


columns may not be known.
 The number and datatypes of the underlying database
column may change at runtime.
 Useful when retrieving a row with the SELECT
statement.

Wipro Confidential 106


The %ROWTYPE Attribute

Examples
 Declare a variable to store the same information about a
department as it is stored in the DEPT table.

dept_record
dept_record dept%ROWTYPE;
dept%ROWTYPE;

 Declare a variable to store the same information about a


employee as it is stored in the EMP table.

emp_record
emp_record emp%ROWTYPE;
emp%ROWTYPE;

Wipro Confidential 107


PL/SQL Tables

 Are composed of two components:


 Primary key of datatype BINARY_INTEGER
 Column of scalar or record datatype
 Increase dynamically because they are unconstrained

Wipro Confidential 108


Creating a PL/SQL Table

Syntax

TYPE
TYPE type_name
type_name IS
IS TABLE
TABLE OF
OF
{column_type
{column_type || variable%TYPE
variable%TYPE
|| table.column%TYPE}
table.column%TYPE} [NOT
[NOT NULL]
NULL]
[INDEX
[INDEX BY
BY BINARY_INTEGER];
BINARY_INTEGER];
identifier
identifier type_name;
type_name;

Declare a PL/SQL variable to store a name.


Example
...
...
TYPE
TYPE ename_table_type
ename_table_type IS
IS TABLE
TABLE OF
OF emp.ename%TYPE
emp.ename%TYPE
INDEX
INDEX BY
BY BINARY_INTEGER;
BINARY_INTEGER;
ename_table
ename_table ename_table_type;
ename_table_type;
...
...

Wipro Confidential 109


PL/SQL Table Structure

Primary Key Column


... ...

1 Jones
2 Smith
3 Maduro

... ...

BINARY_INTEGER Scalar

Wipro Confidential 110


Creating a PL/SQL Table

DECLARE
TYPE ename_table_type IS TABLE OF emp.ename%TYPE
INDEX BY BINARY_INTEGER;
TYPE hiredate_table_type IS TABLE OF DATE
INDEX BY BINARY_INTEGER;
ename_table ename_table_type;
hiredate_table hiredate_table_type;
BEGIN
ename_table(1) := 'CAMERON';
hiredate_table(8) := SYSDATE + 7;
IF ename_table.EXISTS(1) THEN
INSERT INTO ...
...
END;

Wipro Confidential 111


PL/SQL Table of Records

 Define a TABLE variable with the %ROWTYPE attribute.


 Declare a PL/SQL variable to hold department information.

Example

DECLARE
DECLARE
TYPE
TYPE dept_table_type
dept_table_type IS
IS TABLE
TABLE OF
OF dept%ROWTYPE
dept%ROWTYPE
INDEX
INDEX BY
BY BINARY_INTEGER;
BINARY_INTEGER;
dept_table
dept_table dept_table_type;
dept_table_type;
--
-- Each
Each element
element of
of dept_table
dept_table is
is aa record
record

Wipro Confidential 112


Assignment

Wipro Confidential 113


Using
Using PL/SQL
PL/SQL Table
Table Methods
Methods

To make PL/SQL Table easier to use:


 EXISTS  NEXT
 COUNT  EXTEND
 FIRST and LAST  TRIM
 PRIOR  DELETE

Wipro Confidential 114


Summary

 Define and reference PL/SQL variables


 of composite datatypes:
 PL/SQL Records
 PL/SQL Tables
 PL/SQL Table of Records
 Define a PL/SQL Record using the
 %ROWTYPE attribute.

Wipro Confidential 115


Creating Procedures

Wipro Confidential 116


Objectives

After completing this lesson, you should be able to do the


following:
 Describe the uses of procedures
 Create procedures with arguments
 Invoke a procedure
 Remove a procedure

Wipro Confidential 117


Overview of Procedures

 A procedure is a named PL/SQL block that performs an action.


 A procedure can be stored in the database, as a database
object, for repeated execution.

Wipro Confidential 118


Syntax for Creating Procedures

CREATE [OR REPLACE] PROCEDURE procedure_name


(argument1 [mode1] datatype1,
argument2 [mode2] datatype2,
. . .)
IS|AS
PL/SQL Block;

Wipro Confidential 119


Developing Stored Procedures

Editor
Oracle Code
Procedure SQL*Plus Code
1 Builder
Save 2 SQL> START file.sql

Oracle Source code


Compile

p-code

Execute
Wipro Confidential 120
Creating a Stored Procedure Using SQL*Plus

1. Enter the text of the CREATE PROCEDURE


statement in a system editor or word
processor and save it as a script file (.sql
extension).
2. From SQL*Plus, run the script file to
compile the source code into p-code. Use
SHOWERRORS to see any compilation
errors.
3. When successfully compiled, invoke the
procedure from an Oracle Server
environment.

Wipro Confidential 121


Procedural Parameter Modes

Procedure
Calling IN parameter
environment OUT parameter
IN OUT parameter

(DECLARE)

BEGIN

EXCEPTION

END;

Wipro Confidential 122


Parameter Modes for Formal Parameters

IN OUT IN OUT
Default Must be specified Must be specified
Value is Returned to calling Passed into
passed into environment subprogram;
subprogram returned to calling
environment
Formal parameter Uninitialized Initialized variable
acts as a constant variable
Actual parameter Must be a variable Must be a variable
can be a literal,
expression,
constant, or
initialized variable

Wipro Confidential 123


IN Parameters: Example

7369 v_id

SQL> CREATE OR REPLACE PROCEDURE raise_salary


2 (v_id in emp.empno%TYPE)
3 IS
4 BEGIN
5 UPDATE emp
6 SET sal = sal * 1.10
7 WHERE empno = v_id;
8 END raise_salary;
9 /
Procedure created.

SQL> EXECUTE raise_salary (7369)


PL/SQL procedure successfully completed.

Wipro Confidential 124


OUT Parameters: Example

Calling environment QUERY_EMP procedure

7654 v_id
MARTIN v_name

1250 v_salary
1400 v_comm

Wipro Confidential 125


OUT Parameters: Example

SQL> CREATE OR REPLACE PROCEDURE query_emp


1 (v_id IN emp.empno%TYPE,
2 v_name OUT emp.ename%TYPE,
3 v_salary OUT emp.sal%TYPE,
4 v_comm OUT emp.comm%TYPE)
5 IS
6 BEGIN
7 SELECT ename, sal, comm
8 INTO v_name, v_salary, v_comm
9 FROM emp
10 WHERE empno = v_id;
11 END query_emp;
12 /

Wipro Confidential 126


OUT Parameters and SQL*Plus

SQL> START emp_query.sql


Procedure created.

SQL> VARIABLE g_name VARCHAR2(15)


SQL> VARIABLE g_sal NUMBER
SQL> VARIABLE g_comm NUMBER

SQL> EXECUTE query_emp(7654,:g_name,:g_sal,:g_comm)


PL/SQL procedure successfully completed.

SQL> PRINT g_name


G_NAME
---------------
MARTIN

Wipro Confidential 127


IN OUT Parameters

Calling environment FORMAT_PHONE procedure

'8006330575' '(800)633-0575' v_phone_no

SQL> CREATE OR REPLACE PROCEDURE format_phone


2 (v_phone_no IN OUT VARCHAR2)
3 IS
4 BEGIN
5 v_phone_no := '(' || SUBSTR(v_phone_no,1,3) ||
6 ')' || SUBSTR(v_phone_no,4,3) ||
7 '-' || SUBSTR(v_phone_no,7);
8 END format_phone;
9 /

Wipro Confidential 128


Invoking FORMAT_PHONE from SQL*Plus

SQL>VARIABLE g_phone_no VARCHAR2(15)

SQL> BEGIN :g_phone_no := '8006330575'; END;


2 /
PL/SQL procedure successfully completed.
SQL> PRINT g_phone_no
G_PHONE_NO
---------------
8006330575

SQL> EXECUTE format_phone (:g_phone_no)


PL/SQL procedure successfully completed.

SQL> PRINT g_phone_no


G_PHONE_NO
---------------
(800)633-0575
Wipro Confidential 129
Methods for Passing Parameters

 Positional
 Named
 Combination

Wipro Confidential 130


DEFAULT Option for Parameters

SQL> CREATE OR REPLACE PROCEDURE add_dept


1 (v_name IN dept.dname%TYPE DEFAULT 'unknown',
2 v_loc IN dept.loc%TYPE DEFAULT 'unknown')
3 IS
4 BEGIN
5 INSERT INTO dept
6 VALUES (dept_deptno.NEXTVAL, v_name, v_loc);
7 END add_dept;
8 /

Wipro Confidential 131


Examples of Passing Parameters

SQL> BEGIN
2 add_dept;
3 add_dept ( 'TRAINING', 'NEW YORK');
4 add_dept ( v_loc => 'DALLAS', v_name =>'EDUCATION');
5 add_dept ( v_loc => 'BOSTON') ;
6 END;
7 /
PL/SQL procedure successfully completed.

SQL> SELECT * FROM dept;

DEPTNO DNAME LOC


------ -------------- -------------
... ... ...
41 unknown unknown
42 TRAINING NEW YORK
43 EDUCATION DALLAS
44 unknown BOSTON

Wipro Confidential 132


Invoking a Procedure from an Anonymous PL/SQL Block

DECLARE
v_id NUMBER := 7900;
BEGIN
raise_salary(v_id); --invoke procedure
COMMIT;
...

END;

Wipro Confidential 133


Invoking a Procedure from a Stored Procedure

SQL> CREATE OR REPLACE PROCEDURE process_emps


2 IS
3 CURSOR emp_cursor IS
4 SELECT empno
5 FROM emp;
6 BEGIN
7 FOR emp_rec IN emp_cursor
8 LOOP
9 raise_salary(emp_rec.empno); --invoke procedure
10 END LOOP;
11 COMMIT;
12 END process_emps;
13 /

Wipro Confidential 134


Removing Procedures

Using SQL*Plus:

Syntax
DROP PROCEDURE procedure_name

Example
SQL> DROP PROCEDURE raise_salary;
Procedure dropped.

Wipro Confidential 135


Summary

 A procedure is a named PL/SQL block that performs an


action.
 Use parameters to pass data from the calling
environment to the procedure.
 Procedures can be invoked from any tool or language
that supports PL/SQL.
 Procedures can serve as building blocks for an
application.

Wipro Confidential 136


Creating Functions

Wipro Confidential 137


Objectives

 Describe the uses of functions


 Invoke a function
 Remove a function
 Differentiate between a procedure and a function

Wipro Confidential 138


Overview of Stored Functions

 A function is a named PL/SQL block that returns a value.


 A function can be stored in the database, as a database
object, for repeated execution.
 A function can be called as part of an expression.

Wipro Confidential 139


Syntax for Creating Functions

CREATE [OR REPLACE] FUNCTION function_name


(argument1 [mode1] datatype1,
argument2 [mode2] datatype2,
. . .)
RETURN datatype
IS|AS
PL/SQL Block;

The PL/SQL block must have at least one RETURN


statement.

Wipro Confidential 140


Creating a Stored Function Using SQL*Plus: Example

SQL> CREATE OR REPLACE FUNCTION get_sal


2 (v_id IN emp.empno%TYPE)
3 RETURN NUMBER
4 IS
5 v_salary emp.sal%TYPE :=0;
6 BEGIN
7 SELECT sal
8 INTO v_salary
9 FROM emp
10 WHERE empno = v_id;
11 RETURN (v_salary);
12 END get_sal;
13 /

Wipro Confidential 141


Executing Functions

 Invoke a function as part of a PL/SQL expression.


 Create a host variable to hold the returned value.
 Execute the function. The host variable will be
populated by the RETURN value.

Wipro Confidential 142


Executing Functions in SQL*Plus: Example

Calling environment GET_SAL function


7934 v_id

RETURN v_salary

SQL> START get_salary.sql


Function created.
created
SQL> VARIABLE g_salary number
SQL> EXECUTE :g_salary := get_sal(7934)
PL/SQL procedure successfully completed.
SQL> PRINT g_salary
G_SALARY
------------------
1300

Wipro Confidential 143


Advantages of User-Defined Functions in SQL Expressions

 Extend SQL where activities are too complex, too


awkward, or unavailable with SQL

 Can increase efficiency, by using them in the WHERE


clause to filter data, as opposed to filtering the data in
the application
 Can manipulate character strings

Wipro Confidential 144


Locations to Call User-Defined Functions

 Select list of a SELECT command

 Condition of the WHERE and HAVING clauses

 CONNECT BY, START WITH, ORDER BY, and GROUP


BY clauses
 VALUES clauses of the INSERT command

 SET clause of the UPDATE command

Wipro Confidential 145


Calling Functions from SQL Expressions: Restrictions

 A user-defined function must be a stored function.


 A user-defined function must be a ROW function, not a
GROUP function.
 A user-defined function only takes IN parameters,
not OUT, or IN OUT.
 Datatypes must be valid SQL datatypes, CHAR, DATE,
or NUMBER.
 Datatypes cannot be PL/SQL types such as BOOLEAN,
RECORD, or TABLE.

Wipro Confidential 146


Calling Functions from SQL Expressions: Restrictions

 INSERT, UPDATE, or DELETE commands are not allowed.


 Calls to subprograms that break the above restriction are not
allowed.

Wipro Confidential 147


Removing Function

Using SQL*Plus

Syntax
DROP FUNCTION function_name

Example
SQL> DROP FUNCTION get_sal;
Function dropped.

Wipro Confidential 148


Procedure or Function?

Procedure Function
Calling IN argument IN argument
Calling
Environment OUT argument Environment
IN OUT argument

(DECLARE) (DECLARE)

BEGIN BEGIN

EXCEPTION EXCEPTION

END; END;

Wipro Confidential 149


Comparing Procedures and Functions

Procedure Function
Execute as a PL/SQL Invoke as part of an
statement expression
No RETURN datatype Must contain a RETURN
datatype
Can return none, one Must return a single value
or many values

Wipro Confidential 150


Benefits of Stored Procedures and Functions

 Improved performance
 Improved maintenance
 Improved data security and integrity

Wipro Confidential 151


Summary

 A function is a named PL/SQL block that must return a


value.
 A function is invoked as part of an expression.

 A stored function can be called in SQL statements.

Wipro Confidential 152


Creating Packages

Wipro Confidential 153


Objectives

After completing this lesson, you should be able to do the


following:
 Describe packages and list their possible components
 Create a package to group together related variables,
cursors, constants, exceptions, procedures, and
functions
 Make a package construct either public or private
 Invoke a package construct

Wipro Confidential 154


Overview of Packages

 Group logically related PL/SQL types, items, and


subprograms
 Consist of two parts:
 Specification
 Body
 Cannot be called, parameterized, or nested
 Allow Oracle8 to read multiple objects into memory at
once

Wipro Confidential 155


Advantages of Packages

 Modularity
 Easier application design
 Information hiding

Wipro Confidential 156


Advantages of Packages

 Added functionality
 Better performance
 Overloading

Wipro Confidential 157


Developing a Package

1
Package Procedure A
specification declaration 2

4
Procedure B
definition 3
Package
body
Procedure A
definition 2
5

Wipro Confidential 158


Developing a Package

1
Package Procedure A
specification declaration 2

4
Procedure B
definition 3
Package
body
Procedure A
definition 2
5

Wipro Confidential 159


Developing a Package

 Saving the text of the CREATE PACKAGE statement in


two different text files facilitates later modifications to
the package.
 A package specification can exist without a package
body, but a package body cannot exist without a
package specification.
 If you have incorporated a standalone procedure into a
package, you should drop your standalone procedure.

Wipro Confidential 160


Creating the Package Specification

Syntax

CREATE
CREATE [OR
[OR REPLACE]
REPLACE] PACKAGE
PACKAGE package_name
package_name
IS|AS
IS|AS
public
public type
type and
and item
item declarations
declarations
subprogram
subprogram specifications
specifications
END
END package_name;
package_name;

Wipro Confidential 161


Declaring Public Constructs

COMM_PACKAGE package

G_COMM 1
Package
specification
RESET_COMM
procedure 2
declaration

Wipro Confidential 162


Creating a Package Specification: Example

SQL>CREATE OR REPLACE PACKAGE comm_package IS


2 g_comm NUMBER := 10; --initialized to 10
3 PROCEDURE reset_comm
4 (v_comm IN NUMBER);
5 END comm_package;
6 /

Wipro Confidential 163


Referencing a Public Variable and Executing a Public Procedure

SQL>EXECUTE comm_package.g_comm := 5

SQL>EXECUTE comm_package.reset_comm(8)

Wipro Confidential 164


Creating the Package Body

Syntax

CREATE
CREATE [OR
[OR REPLACE]
REPLACE] PACKAGE
PACKAGE BODY
BODY package_name
package_name
IS|AS
IS|AS
private
private type
type and
and item
item declarations
declarations
subprogram
subprogram bodies
bodies
END
END package_name;
package_name;

Wipro Confidential 165


Public and Private Constructs

COMM_PACKAGE package

Package G_COMM 1
specification
RESET_COMM 2
procedure declaration

VALIDATE_COMM
function definition 3
Package
body
RESET_COMM
procedure definition 2

Wipro Confidential 166


Creating a Package Body: Example

SQL> CREATE OR REPLACE PACKAGE BODY comm_package


2 IS
3 FUNCTION validate_comm
4 (v_comm IN NUMBER)
5 RETURN BOOLEAN
6 IS
7 v_max_comm NUMBER;
8 BEGIN
9 SELECT max(comm)
10 INTO v_max_comm
11 FROM emp;
12 IF v_comm > v_max_comm
13 THEN RETURN(FALSE);
14 ELSE RETURN(TRUE);
15 END IF;
16 END validate_comm;

Wipro Confidential 167


Creating a Package Body: Example

17 PROCEDURE reset_comm
18 (v_comm IN NUMBER)
19 IS
20 BEGIN
21 IF validate_comm(v_comm)
22 THEN g_comm:=v_comm; --reset global variable
23 ELSE
24 RAISE_APPLICATION_ERROR
25 (-20210,'Invalid commission');
26 END IF;
27 END reset_comm;
28 END comm_package;
29 /

Wipro Confidential 168


Developing Packages: Guidelines

 Keep packages as general as possible.


 Define the package specification before the body.
 The package specification should only contain public
constructs.
 The package specification should contain as few
constructs as possible.

Wipro Confidential 169


Invoking Package Constructs

Example 1: Invoke a function from a procedure within the


same package.

CREATE OR REPLACE PACKAGE BODY comm_package IS


. . .
PROCEDURE reset_comm
(v_comm IN NUMBER)
IS
BEGIN
IF validate_comm(v_comm)
THEN g_comm := v_comm;
ELSE
RAISE_APPLICATION_ERROR
(-20210, 'Invalid commission');
END IF;
END reset_comm;
END comm_package;

Wipro Confidential 170


Invoking Package Constructs

Example 2: Invoke a package procedure from SQL*Plus.


SQL> EXECUTE comm_package.reset_comm(1500)

Example 3: Invoke a package procedure in a different


schema.
SQL> EXECUTE scott.comm_package.reset_comm(1500)

Example 4: Invoke a package procedure in a remote database.

SQL> EXECUTE comm_package.reset_comm@ny (1500)

Wipro Confidential 171


Referencing a Public Variable Within the Package

Example 1
CREATE OR REPLACE PACKAGE BODY comm_package IS
. . .
PROCEDURE reset_comm
(v_comm IN NUMBER)
IS
BEGIN
IF validate_comm(v_comm);
THEN g_comm := v_comm;
ELSE
RAISE_APPLICATION_ERROR
(-20210, 'Invalid commission');
END IF;
END reset_comm;
END comm_package;

Wipro Confidential 172


Referencing a Public Variable from a Standalone Procedure

Example 2
CREATE OR REPLACE PROCEDURE hire_emp
(v_ename IN emp.ename%TYPE,
v_mgr IN emp.mgr%TYPE,
v_job IN emp.job%TYPE,
v_sal IN emp.sal%TYPE)
IS
v_comm emp.comm%TYPE;
. . .
BEGIN
. . .
v_comm := comm_package.g_comm;
. . .
END hire_emp;

Wipro Confidential 173


Persistent State: Package Variables
Time Scott Jone
09:00 EXECUTE - s
comm_package.reset_comm-
(120) 09:30
INSERT INTO emp
(ename,comm) VALUES
('Madonna',2000);

09:35 EXECUTE -
comm_package.reset_comm-
(170)
10:00 EXECUTE -
comm_package.reset_comm-
(4000)

11:00 ROLLBACK;
11:01 EXIT;
12:00 EXECUTE -
comm_package.reset_comm-
(150)

10 G_COMM 10
120 170
Invalid commission 4000 EXIT
120 10
150

Wipro Confidential 174


Persistent State: Package Cursor

Example

SQL> CREATE OR REPLACE PACKAGE pack_cur


2 IS
3 CURSOR c1 IS SELECT empno FROM emp
4 ORDER BY empno DESC;
5 PROCEDURE proc1_3rows;
6 PROCEDURE proc4_6rows;
7 END pack_cur;
8 /

Wipro Confidential 175


Persistent State: Package Cursor
SQL> CREATE OR REPLACE PACKAGE BODY pack_cur
2 IS
3 v_empno NUMBER;
4 PROCEDURE proc1_3rows IS
5 BEGIN
6 OPEN c1;
7 LOOP
8 FETCH c1 INTO v_empno;
9 DBMS_OUTPUT.PUT_LINE('Id :' ||(v_empno));
10 EXIT WHEN c1%ROWCOUNT >= 3;
11 END LOOP;
12 END proc1_3rows;
13 PROCEDURE proc4_6rows IS
14 BEGIN
15 LOOP
16 FETCH c1 INTO v_empno;
17 DBMS_OUTPUT.PUT_LINE('Id :' ||(v_empno));
18 EXIT WHEN c1%ROWCOUNT >= 6;
19 END LOOP;
20 CLOSE c1;
21 END proc4_6rows;
22 END pack_cur;
23 /

Wipro Confidential 176


Persistent State: Package Cursor

SQL> SET SERVEROUTPUT ON


SQL> EXECUTE pack_cur.proc1_3rows
Id : 7934
Id : 7902
Id : 7900
SQL> EXECUTE pack_cur.proc4_6rows
Id : 7876
Id : 7844
Id : 7839

Wipro Confidential 177


Persistent State: Package PL/SQL Tables and Records

CREATE OR REPLACE PACKAGE emp_package IS


TYPE emp_table_type IS TABLE OF emp%ROWTYPE
INDEX BY BINARY_INTEGER;
PROCEDURE read_emp_table
(emp_table OUT emp_table_type);
END emp_package;

CREATE OR REPLACE PACKAGE BODY emp_package IS


PROCEDURE read_emp_table
(emp_table OUT emp_table_type)
IS
i BINARY_INTEGER := 0;
BEGIN
FOR emp_record IN (SELECT * FROM emp)
LOOP
emp_table(i) := emp_record;
i:= i+1;
END LOOP;
END read_emp_table;
END emp_package;

Wipro Confidential 178


Removing Packages

To remove the package specification and the body:


DROP
DROP PACKAGE
PACKAGE package_name
package_name

To remove the package body:


DROP
DROP PACKAGE
PACKAGE BODY
BODY package_name
package_name

Wipro Confidential 179


Summary

 Improve organization, management, security, and


performance.
 Group related procedures and functions together.
 Change a package body without affecting a package
specification.
 Grant security access to the entire package.

Wipro Confidential 180


Summary

 Hide the source code from users.


 Load the entire package into memory
on the first call.
 Reduce disk access for subsequent calls.
 Provide identifiers for the user session.

Wipro Confidential 181


Summary

Command Task

CREATE [OR REPLACE] Create (or modify) an existing


PACKAGE package specification

CREATE [OR REPLACE] Create (or modify) an existing


PACKAGE BODY package body

DROP PACKAGE Remove both the package


specification and the package body

DROP PACKAGE BODY Remove the package body only

Wipro Confidential 182


Assignment

Wipro Confidential
More Package Concepts

Wipro Confidential 184


Objectives

 After completing this lesson, you should be able to do


the following:

 Write packages that use the overloading feature

 Avoid errors with mutually referential subprograms

 Initialize variables with a one-time-only procedure

Wipro Confidential 185


Objectives

 Control side effects of functions

 Declare and use cursor variables in a package

 Describe the use and application of the Oracle Server


supplied packages

Wipro Confidential 186


Overloading

 Allows you to use the same name for different


subprograms inside a package
 The formal parameters of the subprograms must differ
in number, order, or datatype family
 Overloaded subprograms can be placed in local or
packaged subprograms

Wipro Confidential 187


Overloading: Example

CREATE OR REPLACE PACKAGE BODY over_pack


IS
PROCEDURE add_dept
(v_deptno IN dept.deptno%TYPE,
v_name IN dept.dname%TYPE DEFAULT 'unknown',
v_loc IN dept.loc%TYPE DEFAULT 'unknown')
IS
BEGIN
INSERT INTO dept
VALUES (v_deptno,v_name,v_loc);
END add_dept;
PROCEDURE add_dept
(v_name IN dept.dname%TYPE DEFAULT 'unknown',
v_loc IN dept.loc%TYPE DEFAULT 'unknown')
IS
BEGIN
INSERT INTO dept
VALUES (dept_deptno.NEXTVAL,v_name,v_loc);
END add_dept;
END over_pack;

Wipro Confidential 188


Forward Declarations

Identifiers must be declared before referencing them.

CREATE OR REPLACE PACKAGE BODY forward_pack


IS
. . .
PROCEDURE award_bonus(. . .)
IS
BEGIN
calc_rating(. . .); --illegal reference
. . .
END;
PROCEDURE calc_rating(. . .)
IS
BEGIN
. . .
END;
. . .
END forward_pack;

Wipro Confidential 189


Forward Declarations

CREATE OR REPLACE PACKAGE BODY forward_pack


IS
. . .
PROCEDURE calc_rating(. . .); -- forward declaration
. . .
PROCEDURE award_bonus(. . .)
IS -- subprograms defined
BEGIN -- in alphabetical order
calc_rating(. . .);
. . .
END;

PROCEDURE calc_rating(. . .)
IS
BEGIN
. . .
END;
. . .
END forward_pack;

Wipro Confidential 190


Creating a One-Time-Only Procedure

CREATE OR REPLACE PACKAGE BODY comm_package


IS
FUNCTION validate_comm
. . .
END validate_comm;

PROCEDURE reset_comm
. . .
END reset_comm;

BEGIN
SELECT AVG(comm)
INTO g_comm
FROM emp;
END comm_package;

Wipro Confidential 191


Restrictions on Package Functions Used in SQL

 INSERT, UPDATE, or DELETE are not allowed.


 Only local functions can update package variables.
 Remote functions cannot read or write remote package
variables.
 Functions that read or write package variables cannot use the
parallel query option.
 Calls to subprograms that break the above restrictions are not
allowed.

Wipro Confidential 192


Purity Level of a Package Function

PRAGMA RESTRICT_REFERENCES (function_name,


WNDS
[,WNPS]
[,RNDS]
[,RNPS] );

Wipro Confidential 193


PRAGMA RESTRICT_REFERENCES

CREATE OR REPLACE PACKAGE taxes


AS
FUNCTION tax
(v_value IN NUMBER)
RETURN NUMBER;
PRAGMA RESTRICT_REFERENCES (tax, WNDS, RNPS, WNPS);
END taxes;

CREATE OR REPLACE PACKAGE BODY taxes


AS
FUNCTION tax
(v_value IN NUMBER)
RETURN NUMBER
IS
BEGIN
RETURN (v_value * 0.08);
END tax;
END taxes;

Wipro Confidential 194


Invoke a User-Defined Package Function from a SQL Statement

SQL> SELECT taxes.tax(sal), sal,ename


2 FROM emp
3 /
TAXES.TAX(SAL) SAL ENAME
-------------- --------- ----------
400 5000 KING
228 2850 BLAKE
196 2450 CLARK
238 2975 JONES
100 1250 MARTIN
128 1600 ALLEN
120 1500 TURNER
76 950 JAMES
100 1250 WARD
240 3000 FORD
64 800 SMITH
240 3000 SCOTT
88 1100 ADAMS
104 1300 MILLER
14 rows selected.

Wipro Confidential 195


Cursor Variables and Packages

CREATE OR REPLACE PACKAGE emp_data -- package specification


AS
. . .
TYPE emp_cur_typ IS
REF CURSOR RETURN emp%ROWTYPE; --define type

PROCEDURE use_emp_cv(emp_cv IN OUT emp_cur_typ);


END emp_data;

CREATE OR REPLACE PACKAGE BODY emp_data -- package body


AS
. . .
PROCEDURE use_emp_cv(emp_cv IN OUT emp_cur_typ)
IS
BEGIN
OPEN emp_cv FOR SELECT * FROM emp;
END use_emp_cv;
. . .
END emp_data;

Wipro Confidential 196


Oracle Supplied Packages

Several packaged procedures are provided with the Oracle Server


to allow either PL/SQL access to certain SQL features or to
extend the functionality of the database.

 DBMS_ALERT  DBMS_JOB
 DBMS_APPLICATION_INFO  DBMS_LOCK
 DBMS_DDL  DBMS_OUTPUT
 DBMS_DESCRIBE

Wipro Confidential 197


Oracle Supplied Packages

Several packaged procedures are provided with the Oracle Server


to allow either PL/SQL access to certain SQL features or to
extend the functionality of the database.

 DBMS_PIPE  DBMS_TRANSACTION
 DBMS_SESSION  DBMS_UTILITY
 DBMS_SHARED_POOL  UTL_FILE
 DBMS_SQL

Wipro Confidential 198


Using DBMS_PIPE

Session 1 Session 2

DEMO_PIPE

Pack_message Receive_message

Send_message Unpack_message

Wipro Confidential 199


Using DBMS_PIPE
CREATE OR REPLACE PROCEDURE send_message
(v_message IN VARCHAR2)
IS s INTEGER;
BEGIN
DBMS_PIPE.PACK_MESSAGE(v_message);
s := DBMS_PIPE.SEND_MESSAGE('DEMO_PIPE');
IF s <> 0
THEN RAISE_APPLICATION_ERROR (-20200,
'Error '||TO_CHAR(s)||' sending on pipe.');
END IF;
END send_message;

CREATE OR REPLACE PROCEDURE receive_message


IS s INTEGER;
v_message VARCHAR2(50);
BEGIN
s := DBMS_PIPE.RECEIVE_MESSAGE('DEMO_PIPE');
IF s <> 0
THEN RAISE_APPLICATION_ERROR (-20200,
'Error '||TO_CHAR(s)||' reading pipe.');
END IF;
DBMS_PIPE.UNPACK_MESSAGE(v_message);
DBMS_OUTPUT.PUT_LINE(v_message);
END receive_message;
Wipro Confidential 200
DBMS_PIPE Package

 Some of the procedures/functions of the


 package:
 PACK_MESSAGE
 PACK_MESSAGE_RAW
 PACK_MESSAGE_ROWID
 SEND_MESSAGE
 RECEIVE_MESSAGE

Wipro Confidential 201


DBMS_PIPE Package

 UNPACK_MESSAGE
 UNPACK_MESSAGE_RAW
 UNPACK_MESSAGE_ROWID
 NEXT_ITEM_TYPE
 UNIQUE_SESSION_NAME
 PURGE

Wipro Confidential 202


DBMS_SQL Package

 DBMS_SQL is used to write Dynamic SQL.

 DBMS_SQL allows:
 Object names to be supplied at runtime rather than at
compilation time
 DDL statements to be executed in PL/SQL

Wipro Confidential 203


DBMS_SQL Execution Flow

open_cursor

PARSE

Use bind No
variables?
Yes

bind_variable

Yes
query?
No
EXECUTE define_column

1 2

Wipro Confidential 204


DBMS_SQL Execution Flow

1 2

PL/SQL No
EXECUTE
block?

Yes
fetch_rows

variable_value
column_value
variable_value

close_cursor

Wipro Confidential 205


Using DBMS_SQL

CREATE OR REPLACE PROCEDURE delete_all_rows


(tab_name IN VARCHAR2,
rows_del OUT NUMBER)
IS
cursor_name INTEGER;
BEGIN
cursor_name := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE ( cursor_name, 'delete FROM ||tab_name,
DBMS_SQL.NATIVE );
rows_del := DBMS_SQL.EXECUTE (cursor_name);
DBMS_SQL.CLOSE_CURSOR(cursor_name);
END;

Use dynamic SQL to delete rows


SQL> VARIABLE deleted NUMBER
SQL> EXECUTE delete_all_rows('emp',:deleted)
PL/SQL procedure successfully completed.
SQL> PRINT deleted
DELETED
---------
14

Wipro Confidential 206


DBMS_SQL Package

 Some of the procedures/functions of the


 package:
 OPEN_CURSOR
 PARSE
 BIND_VARIABLE
 DEFINE_COLUMN
 EXECUTE
 FETCH_ROWS
 EXECUTE_AND_FETCH

Wipro Confidential 207


DBMS_SQL Package

 COLUMN_VALUE
 COLUMN_VALUE_CHAR
 COLUMN_VALUE_RAW
 COLUMN_VALUE_ROWID
 VARIABLE_VALUE
 VARIABLE_VALUE_CHAR
 VARIABLE_VALUE_RAW
 VARIABLE_VALUE_ROWID

Wipro Confidential 208


DBMS_SQL Package

 IS_OPEN
 CLOSE_CURSOR
 LAST_ERROR_POSITION
 LAST_ROW_COUNT
 LAST_ROW_ID
 LAST_SQL_FUNCTION_CODE

Wipro Confidential 209


Using DBMS_SQL: Example

CREATE OR REPLACE PROCEDURE exec_select


(v_table_name IN VARCHAR2,
v_column_name IN VARCHAR2,
v_column_value IN VARCHAR2,
v_row OUT VARCHAR2)
IS
mycursor INTEGER;
myreturn INTEGER;
v_ename VARCHAR2(100);
v_sal NUMBER;
sql_statement VARCHAR2(200) := 'SELECT ename, sal FROM '
||v_table_name ||' WHERE '
||v_column_name||'=UPPER(:col_value)';
err_code NUMBER;
err_msg VARCHAR2(100);
BEGIN
mycursor := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(mycursor,sql_statement,DBMS_SQL.native);
DBMS_SQL.BIND_VARIABLE(mycursor,'col_value',v_column_value);
DBMS_SQL.DEFINE_COLUMN(mycursor,1,v_ename,100);
DBMS_SQL.DEFINE_COLUMN(mycursor,2,v_sal);

Wipro Confidential 210


Using DBMS_SQL: Example

myreturn := DBMS_SQL.EXECUTE(mycursor);
LOOP
myreturn := DBMS_SQL.FETCH_ROWS(mycursor);
EXIT WHEN myreturn = 0;
DBMS_SQL.COLUMN_VALUE(mycursor,1,v_ename);
DBMS_SQL.COLUMN_VALUE(mycursor,2,v_sal);
IF v_row IS NULL
THEN v_row := v_ename||''||v_sal;
ELSE v_row := v_row||CHR(10)||v_ename||' '||v_sal;
END IF;
END LOOP;
DBMS_SQL.CLOSE_CURSOR(mycursor);
EXCEPTION
WHEN others
THEN err_code := SQLCODE;
err_msg := SUBSTR(SQLERRM,1,100);
RAISE_APPLICATION_ERROR ( -20202 ,
'Error number is: '||TO_CHAR(err_code) ||'
Full error is : '||err_msg);
END exec_select;

Wipro Confidential 211


Invoking the General Purpose Procedure

SQL> VARIABLE v_out1 VARCHAR2(60)

SQL> SET serveroutput ON

SQL> EXECUTE exec_select('&table_name' ,'&column_name',-


> '&column_value',:v_out1)
Enter value for table_name: emp
Enter value for column_name: job
Enter value for column_value: manager

PL/SQL procedure successfully completed.

SQL> PRINT v_out1

V_OUT1
--------------------------------------------------
BLAKE 2850
CLARK 2450
JONES 2975

Wipro Confidential 212


DBMS_OUTPUT Package

 Allows you to output messages from


 PL/SQL blocks.
 Some of the procedures of the package:
 PUT
 NEW_LINE
 PUT_LINE
 GET_LINE
 GET_LINES
 ENABLE/DISABLE

Wipro Confidential 213


Summary

 Additional features of packages:


 Overloading
 Forward Referencing
 One-time-only procedures
 Purity level of package functions

Wipro Confidential 214


Summary

 Oracle Server supplied packages:


 You can take advantage of a number of preconfigured
packages supplied by the Oracle Server.
 All packages are installed in the script catproc.sql or
each one can be installed individually.
 You can use packages as libraries of
 routines when developing a database
 application.

Wipro Confidential 215


Assignment

Wipro Confidential
Creating Database Triggers

Wipro Confidential 217


Objectives

 After completing this lesson, you should be able to do


the following:

 Describe database triggers and their use


 Create database triggers
 Describe database trigger firing rules
 Remove database triggers

Wipro Confidential 218


Overview of Triggers

 A trigger is a PL/SQL block that executes implicitly


whenever a particular event takes place.
 A trigger can be either a database trigger or an
application trigger.

Wipro Confidential 219


Designing Triggers: Guidelines

 Design triggers to:


 Perform related actions
 Centralize global operations

 Do not design triggers:


 Where functionality already exists
 Which duplicate other triggers

Wipro Confidential 220


Creating Triggers

Trigger timing: BEFORE, AFTER or


INSTEAD OF (view)
Triggering event: INSERT, UPDATE or
DELETE
Table name: On table/view
Trigger type: Row or statement
When clause: Restricting condition
Trigger body: DECLARE
BEGIN
EXCEPTION
END;

Wipro Confidential 221


Trigger Components

Trigger timing: When should the trigger fire?


 BEFORE: The code in the trigger body will execute before the
triggering DML event.
 AFTER: The code in the trigger body will execute after the
triggering DML event.

Wipro Confidential 222


Trigger Components

Trigger timing: When should the trigger fire?


 INSTEAD OF: The code in the trigger body will execute instead
of the the triggering statement. Used for VIEWS that are not
otherwise modifiable.

Wipro Confidential 223


Trigger Components

Triggering event:
What DML operation will cause the trigger to execute?
 INSERT
 UPDATE
 DELETE
 Any combination of the above

Wipro Confidential 224


Trigger Components

Trigger type:

How many times should the trigger body execute when

the triggering event takes place?

 Statement: The trigger body executes once for the

triggering event. This is the default.

 Row: The trigger body executes once for each row

affected by the triggering event.

Wipro Confidential 225


Trigger Components

 Trigger body:
 What action should the trigger perform?
 The trigger body is defined with an anonymous PL/SQL
block.
 [DECLARE]
 BEGIN
 [EXCEPTION]
 END;

Wipro Confidential 226


Firing Sequence of Database Triggers on a Single Row

BEFORE statement trigger


DEPT table
DEPTNO DNAME LOC
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS BEFORE row trigger
30 SALES CHICAGO AFTER row trigger
40 OPERATIONS BOSTON

AFTER statement trigger

Wipro Confidential 227


Statement and Row Triggers

Example 1

SQL>
SQL> INSERT
INSERT INTO
INTO dept
dept (deptno,
(deptno, dname,
dname, loc)
loc)
22 VALUES
VALUES (50,
(50, 'EDUCATION',
'EDUCATION', 'NEW
'NEW YORK');
YORK');

Example 2

SQL>
SQL> UPDATE
UPDATE emp
emp
22 SET
SET sal
sal == sal
sal ** 1.1
1.1
33 WHERE
WHERE deptno
deptno == 30;
30;

Wipro Confidential 228


Firing Sequence of Database Triggers on Multiple Rows

BEFORE statement trigger

EMPNO ENAME DEPTNO


BEFORE row trigger
7839 KING 30 AFTER row trigger
7698 BLAKE 30 BEFORE row trigger
AFTER row trigger
7788 SMITH 30 BEFORE row trigger
AFTER row trigger

AFTER statement trigger

Wipro Confidential 229


Syntax for Creating Statement Triggers

CREATE
CREATE [OR
[OR REPLACE]
REPLACE] TRIGGER
TRIGGER trigger_name
trigger_name
timing
timing event1
event1 [OR
[OR event2
event2 OR
OR event3]
event3]
ON
ON table_name
table_name
PL/SQL
PL/SQL block;
block;

Wipro Confidential 230


Before Statement Trigger: Example

SQL>
SQL> CREATE
CREATE OR
OR REPLACE
REPLACE TRIGGER
TRIGGER secure_emp
secure_emp
22 BEFORE
BEFORE INSERT
INSERT ON
ON emp
emp
33 BEGIN
BEGIN
44 IF
IF (TO_CHAR
(TO_CHAR (sysdate,'DY')
(sysdate,'DY') ININ ('SAT','SUN'))
('SAT','SUN')) OR
OR
55 (TO_CHAR(sysdate,'HH24')
(TO_CHAR(sysdate,'HH24') NOT
NOT BETWEEN
BETWEEN
66 '08'
'08' AND
AND '18')
'18')
77 THEN
THEN RAISE_APPLICATION_ERROR
RAISE_APPLICATION_ERROR (-20500,
(-20500,
88 'You
'You may
may only
only insert
insert into
into EMP
EMP during
during normal
normal hours.');
hours.');
99 END
END IF;
IF;
10
10 END;
END;
11
11 //

Wipro Confidential 231


Example

SQL>
SQL> INSERT
INSERT INTO
INTO emp
emp (empno,
(empno, ename,
ename, deptno)
deptno)
22 VALUES
VALUES (7777,
(7777, 'BAUWENS',
'BAUWENS', 40);
40);
INSERT
INSERT INTO
INTO emp
emp (empno,
(empno, ename,
ename, deptno)
deptno)
**
ERROR
ERROR at
at line
line 1:
1:
ORA-20500:
ORA-20500: You
You may
may only
only insert
insert into
into EMP
EMP during
during normal
normal hours.
hours.
ORA-06512:
ORA-06512: at
at "SCOTT.SECURE_EMP",
"SCOTT.SECURE_EMP", line
line 44
ORA-04088:
ORA-04088: error
error during
during execution
execution of
of trigger
trigger
'SCOTT.SECURE_EMP'
'SCOTT.SECURE_EMP'

Wipro Confidential 232


Using Conditional Predicates
SQL>CREATE OR REPLACE TRIGGER secure_emp
2 BEFORE INSERT OR UPDATE OR DELETE ON emp
3 BEGIN
4 IF (TO_CHAR (sysdate,'DY') IN ('SAT','SUN')) OR
5 (TO_CHAR (sysdate, 'HH24') NOT BETWEEN '08' AND '18')
6 THEN
7 IF DELETING
8 THEN RAISE_APPLICATION_ERROR (-20502,
9 'You may only delete from EMP during normal hours.');
10 ELSIF INSERTING
11 THEN RAISE_APPLICATION_ERROR (-20500,
12 'You may only insert into EMP during normal hours.');
13 ELSIF UPDATING ('SAL')
14 THEN RAISE_APPLICATION_ERROR (-20503,
15 'You may only update SAL during normal hours.');
16 ELSE
17 RAISE_APPLICATION_ERROR (-20504,
18 'You may only update EMP during normal hours.');
19 END IF;
20 END IF;
21 END;
22 /

Wipro Confidential 233


After Statement Trigger: Example

SQL>CREATE
SQL>CREATE OR OR REPLACE
REPLACE TRIGGER
TRIGGER check_salary_count
check_salary_count
22 AFTER
AFTER UPDATE
UPDATE OF
OF sal
sal ON
ON emp
emp
33 DECLARE
DECLARE
44 v_salary_changes
v_salary_changes NUMBER;
NUMBER;
55 v_max_changes
v_max_changes NUMBER;
NUMBER;
66 BEGIN
BEGIN
77 SELECT
SELECT upd,
upd, max_upd
max_upd
88 INTO
INTO v_salary_changes,
v_salary_changes, v_max_changes
v_max_changes
99 FROM
FROM audit_table
audit_table
10
10 WHERE
WHERE user_name
user_name == user
user
11
11 AND
AND tablename
tablename == 'EMP'
'EMP'
12
12 AND
AND column_name
column_name == 'SAL';
'SAL';
13
13 IF
IF v_salary_changes
v_salary_changes >> v_max_changes
v_max_changes THEN
THEN
14
14 RAISE_APPLICATION_ERROR
RAISE_APPLICATION_ERROR (-20501,
(-20501,
15
15 'You
'You may only make a maximum of
may only make a maximum of '||
'||
16
16 TO_CHAR
TO_CHAR (v_max_changes)
(v_max_changes) ||||
17
17 '' changes
changes to
to the
the SAL
SAL column');
column');
18
18 END
END IF;
IF;
19
19 END;
END;
20
20 //

Wipro Confidential 234


Audit_Table

USER_NAME TABLENAME COLUMN_NAME INS UPD DEL


SCOTT EMP 1 1 1
SCOTT EMP SAL 1
JONES EMP 0 0 0

Continuation
MAX_INS MAX_UPD MAX_DEL
5 5 5
5
5 0 0

Wipro Confidential 235


Creating a Row Trigger

CREATE
CREATE [OR
[OR REPLACE]
REPLACE] TRIGGER
TRIGGER trigger_name
trigger_name
timing
timing event1
event1 [OR
[OR event2
event2 OROR event3]
event3]
ON
ON table_name
table_name
[REFERENCING
[REFERENCING OLD
OLD AS
AS old
old || NEW
NEW AS
AS new]
new]
FOR
FOR EACH
EACH ROW
ROW
[WHEN
[WHEN condition]
condition]
PL/SQL
PL/SQL block;
block;

Wipro Confidential 236


After Row Trigger: Example

SQL>CREATE OR REPLACE TRIGGER audit_emp


2 AFTER DELETE OR INSERT OR UPDATE ON emp
3 FOR EACH ROW
4 BEGIN
5 IF DELETING THEN
6 UPDATE audit_table SET del = del + 1
7 WHERE user_name = user AND tablename = 'EMP'
8 AND column_name IS NULL;
9 ELSIF INSERTING THEN
10 UPDATE audit_table SET ins = ins + 1
11 WHERE user_name = user AND tablename = 'EMP'
12 AND column_name IS NULL;
13 ELSIF UPDATING ('SAL') THEN
14 UPDATE audit_table SET upd = upd + 1
15 WHERE user_name = user AND tablename = 'EMP'
16 AND column_name = 'SAL';
17 ELSE /* A general UPDATE. */
18 UPDATE audit_table SET upd = upd + 1
19 WHERE user_name = user AND tablename = 'EMP'
20 AND column_name IS NULL;
21 END IF;
22 END;
23 /

Wipro Confidential 237


Using Old and New Qualifiers

SQL>CREATE OR REPLACE TRIGGER audit_emp_values


2 AFTER DELETE OR INSERT OR UPDATE ON emp
3 FOR EACH ROW
4 BEGIN
5 INSERT INTO audit_emp_table (user_name,
6 timestamp, id, old_last_name, new_last_name,
7 old_title, new_title, old_salary, new_salary)
8 VALUES (USER, SYSDATE, :OLD.empno, :OLD.ename,
9 :NEW.ename, :OLD.job, :NEW.job,
10 :OLD.sal, :NEW.sal );
11 END;
12 /

Wipro Confidential 238


Audit_Emp_Table

USER_NAME TIMESTAMP ID OLD_LAST_NAME NEW_LAST_NAME


EGRAVINA 12-NOV-97 NULL NULL HUTTON

NGREENBE 10-DEC-97 7844 MAGEE TURNER

Continuation
OLD_TITLE NEW_TITLE OLD_SALARY NEW_SALARY
NULL ANALYST NULL 3500

CLERK SALESMAN 1100 1100

Wipro Confidential 239


Restricting a Row Trigger

SQL>CREATE OR REPLACE TRIGGER derive_commission_pct


2 BEFORE INSERT OR UPDATE OF sal ON emp
3 FOR EACH ROW
4 WHEN (NEW.job = 'SALESMAN')
5 BEGIN
6 IF INSERTING
7 THEN :NEW.comm := 0;
8 ELSIF :OLD.comm IS NULL
9 THEN :NEW.comm := 0;
10 ELSE :NEW.comm := :OLD.comm * (:NEW.sal/:OLD.sal);
11 END IF;
12 END;
13 /

Wipro Confidential 240


Differentiating Between Triggers and Stored Procedures

Triggers Procedure

Use CREATE TRIGGER Use CREATE PROCEDURE

Data dictionary contains source Data dictionary contains


and p-code source and p-code

Implicitly invoked Explicitly invoked

COMMIT, SAVEPOINT, COMMIT, SAVEPOINT,


ROLLBACK not allowed ROLLBACK allowed

Wipro Confidential 241


Managing Triggers

Disable or re-enable a database trigger


ALTER
ALTER TRIGGER
TRIGGER trigger_name
trigger_name DISABLE
DISABLE || ENABLE
ENABLE

Disable or re-enable all triggers for a table


ALTER
ALTER TABLE
TABLE table_name
table_name DISABLE
DISABLE || ENABLE
ENABLE ALL
ALL TRIGGERS
TRIGGERS

Recompile a trigger for a table


ALTER
ALTER TRIGGER
TRIGGER trigger_name
trigger_name COMPILE
COMPILE

Wipro Confidential 242


Removing Triggers

To remove a trigger from the database, use the DROP TRIGGER
syntax:

DROP
DROP TRIGGER
TRIGGER trigger_name
trigger_name

• Example
SQL>
SQL> DROP
DROP TRIGGER
TRIGGER secure_emp;
secure_emp;
Trigger
Trigger dropped
dropped

Wipro Confidential 243


Rules Governing Triggers

 Rule 1: Do not change data in the primary key, foreign


key, or unique key columns of a constraining table.
 Rule 2: Do not read data from a mutating table.

Wipro Confidential 244


Changing Data in a Constraining Table

Triggering event
SQL>
SQL> UPDATE
UPDATE dept
dept
Trigger action
22 SET
SET id
id == 11
33 WHERE
WHERE id
id == 30;
30;

EMP table Referential integrity DEPT table


EMPNO ENAME DEPTNO DEPTNO DNAME
7698 BLAKE 30 10 ACCOUNTING
7654 MARTIN 30 20 RESEARCH
7499 ALLEN 30 30 SALES
40 OPERATIONS
Constraining AFTER UPDATE
table Failure row Triggered
table
xxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxx
vvvvvvvvvvvvvvvvvvvvvvvvvvvv
vvvvvvvvvvvvvvvvvvvvvvvvvvvv
xxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxx
vvvvvvvvvvvvvvvvvvvvvvvvvvvv
CASCADE_UPDATES
vvvvvvvvvvvvvvvvvvvvvvvvvvvv
xxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxx trigger

Wipro Confidential 245


Constraining Table: Example

SQL>
SQL> CREATE
CREATE OR
OR REPLACE
REPLACE TRIGGER
TRIGGER cascade_updates
cascade_updates
22 AFTER
AFTER UPDATE
UPDATE OF
OF deptno
deptno on
on DEPT
DEPT
33 FOR
FOR EACH
EACH ROW
ROW
44 BEGIN
BEGIN
55 UPDATE
UPDATE emp
emp
66 SET
SET emp.deptno
emp.deptno == :new.deptno
:new.deptno
77 WHERE
WHERE emp.deptno
emp.deptno == :old.deptno;
:old.deptno;
88 END;
END;
99 //

Wipro Confidential 246


Constraining Table: Example

SQL>
SQL> UPDATE
UPDATE dept
dept
22 SET
SET deptno
deptno == 11
33 WHERE
WHERE deptno
deptno == 30;
30;
**
ERROR
ERROR at
at line
line 1:
1:
ORA-04091:
ORA-04091: table
table DEPT
DEPT is is mutating,
mutating, trigger/function
trigger/function
may
may not
not see
see it
it
ORA-06512:
ORA-06512: at
at "CASCADE_UPDATES",
"CASCADE_UPDATES", line
line 22
ORA-04088:
ORA-04088: error
error during
during execution
execution of
of trigger
trigger
'CASCADE_UPDATES'
'CASCADE_UPDATES'

Wipro Confidential 247


Reading Data from a Mutating Table

SQL>
SQL> UPDATE
UPDATE emp
emp
22 SET
SET sal
sal == 1500
1500
33 WHERE
WHERE ename
ename == 'SMITH';
'SMITH';

Failure CHECK_SALARY
EMP table trigger
EMPNO ENAME JOB SAL
7369 SMITH CLERK 1500
7698 BLAKE MANAGER 2850
7788 SCOTT ANALYST 3000
BEFORE
Trigged table/
UPDATE
mutating table
row
Trigger event

Wipro Confidential 248


Mutating Table: Example

SQL>
SQL> CREATE
CREATE OR
OR REPLACE
REPLACE TRIGGER
TRIGGER check_salary
check_salary
22 BEFORE
BEFORE INSERT
INSERT OROR UPDATE
UPDATE OF
OF sal,
sal, job
job ON
ON emp
emp
33 FOR
FOR EACH
EACH ROW
ROW
44 WHEN
WHEN (new.job
(new.job <><> 'PRESIDENT')
'PRESIDENT')
55 DECLARE
DECLARE
66 v_minsalary
v_minsalary emp.sal%TYPE;
emp.sal%TYPE;
77 v_maxsalary
v_maxsalary emp.sal%TYPE;
emp.sal%TYPE;
88 BEGIN
BEGIN
99 SELECT
SELECT MIN(sal),
MIN(sal), MAX(sal)
MAX(sal)
10
10 INTO
INTO v_minsalary,
v_minsalary, v_maxsalary
v_maxsalary
11
11 FROM
FROM emp
emp
12
12 WHERE
WHERE jobjob == :new.job;
:new.job;
13
13 IF
IF :new.sal
:new.sal << v_minsalary
v_minsalary OR
OR
14
14 :new.sal
:new.sal >> v_maxsalary
v_maxsalary THEN
THEN
15
15 RAISE_APPLICATION_ERROR(-20505,'Out
RAISE_APPLICATION_ERROR(-20505,'Out of of range');
range');
16
16 END
END IF;
IF;
17
17 END;
END;
18
18 //

Wipro Confidential 249


Mutating Table: Example

SQL>
SQL> UPDATE
UPDATE emp
emp
22 SET
SET sal
sal == 1500
1500
33 WHERE
WHERE ename
ename == 'SMITH';
'SMITH';
**
ERROR
ERROR at
at line
line 2:
2:
ORA-04091:
ORA-04091: table
table EMP
EMP is
is mutating,
mutating, trigger/function
trigger/function
may
may not
not see
see it
it
ORA-06512:
ORA-06512: at
at "CHECK_SALARY",
"CHECK_SALARY", line
line 55
ORA-04088:
ORA-04088: error
error during
during execution
execution of
of trigger
trigger
'CHECK_SALARY'
'CHECK_SALARY'

Wipro Confidential 250


Implementation of Triggers

 Security
 Auditing
 Data integrity
 Referential integrity
 Table replication
 Derived data
 Event logging

Wipro Confidential 251


Benefits of Database Triggers

 Improved data security

 Provide value-based security checks

 Provide value-based auditing

 Improved data integrity

 Enforce dynamic data integrity constraints

 Enforce complex referential integrity constraints

 Ensure related operations are performed together


implicitly

Wipro Confidential 252


Assignment

Wipro Confidential
Managing Subprograms

Wipro Confidential 254


Objectives

After completing this lesson, you should be able to do the


following:
 Describe system privilege requirements
 Describe object privilege requirements
 Track procedural dependencies
 Predict the effect of changing a database object upon
stored procedures and functions
 Manage procedural dependencies
 Debug subprograms

Wipro Confidential 255


Privileges Required

System privileges
CREATE (ANY) PROCEDURE
 TRIGGER
ALTER ANY PROCEDURE
 TRIGGER
DROP ANY PROCEDURE
DBA grants  TRIGGER
EXECUTE ANY PROCEDURE

Object privilege
Owner grants EXECUTE
EXECUTE

Wipro Confidential 256


Example

DIRECT ACCESS
SQL>
SQL> GRANT
GRANT select
select
22 ON
ON emp
emp
33 TO
TO scott;
scott;
Grant
Grant Succeeded.
Succeeded.

INDIRECT ACCESS

SQL>
SQL> GRANT
GRANT execute
execute
22 ON
ON query_emp
query_emp
33 TO
TO green;
green;
Grant
Grant Succeeded.
Succeeded.

Wipro Confidential 257


Managing Stored PL/SQL Objects

Data dictionary

General
Source code
information
Editor

Parameters p-code

Compile Debug SQL> DESCRIBE ...


errors information
DBMS_OUTPUT

Procedure Builder

Wipro Confidential 258


USER_OBJECTS *

Column Column Description

OBJECT_NAME Name of the object

OBJECT_ID Internal identifier for the object

OBJECT_TYPE Type of object, for example, TABLE,


PROCEDURE, FUNCTION, PACKAGE,
PACKAGE BODY, TRIGGER

CREATED Date when the object was created

LAST_DDL_TIME Date when the object was last modified

TIMESTAMP Date and time when the object was last


recompiled

STATUS VALID or INVALID


* Abridged column list

Wipro Confidential 259


USER_SOURCE

Column Column Description

NAME Name of the object

TYPE Type of object, for example, PROCEDURE,


FUNCTION, PACKAGE, PACKAGE BODY

LINE Line number of the source code

TEXT Text of the source code line

Wipro Confidential 260


USER_ERRORS
USER_ERRORS

Column Column Description

NAME Name of the object

TYPE Type of object, for example, PROCEDURE,


FUNCTION, PACKAGE, PACKAGE BODY

SEQUENCE Sequence number, for ordering

LINE Line number of the source code at which the


error occurs

POSITION Position in the line at which the error occurs

TEXT Text of the error message

Wipro Confidential 261


USER_TRIGGERS
USER_TRIGGERS
*

Column Column Description

TRIGGER_NAME Name of the trigger

TRIGGER_TYPE The type is, BEFORE, AFTER, INSTEAD OF

TRIGGERING_EVENT The DML operation firing the trigger

TABLE_NAME Name of the database table

REFERENCING_NAMES Name used for :OLD and :NEW

WHEN_CLAUSE The when_clause used

STATUS The status of the trigger

TRIGGER_BODY The action to take


* Abridged column list

Wipro Confidential 262


Understanding
Understanding Dependencies
Dependencies

Dependent objects Referenced objects


Table
Table
View
View
View
View
Procedure
Procedure
Sequence
Sequence
Function
Function
Synonym
Synonym
Package
Packagespecification
specification
Procedure
Procedure
Package
Packagebody
body
Function
Function
Database
Databasetrigger
trigger
Package
Packagespecification
specification

Wipro Confidential 263


Dependencies
Dependencies

View/
Procedure procedure Table
xxxxxxxxxxxxxx
vvvvvvvvvvvvvv
xxxxxxxxxxxxxx
Direct Direct
vvvvvvvvvvvvvv
xxxxxxxxxxxxxx dependency dependency
vvvvvvvvvvvvvv
xxxxxxxxxxxxxx
vvvvvvvvvvvvvv
xxxxxxxxxxxxxx
vvvvvvvvvvvvvv Referenced
Dependent

Dependent Indirect Referenced


dependency

Wipro Confidential 264


Local
Local Dependencies
Dependencies

Procedure Procedure View Table


xxxxxxxxxxxxxx vvvvvvvvvvvvvv
vvvvvvvvvvvvvv xxxxxxxxxxxxxx
xxxxxxxxxxxxxx vvvvvvvvvvvvvv
vvvvvvvvvvvvvv xxxxxxxxxxxxxx
xxxxxxxxxxxxxx vvvvvvvvvvvvvv
vvvvvvvvvvvvvv xxxxxxxxxxxxxx
vvvvvvvvvvvvvv vvvvvvvvvvvvvv

INVALID INVALID INVALID

Local references

Direct local Definition


dependency change

The Oracle Server implicitly recompiles any


INVALID object when the object is next called.

Wipro Confidential 265


Remote
Remote Dependencies
Dependencies

Procedure Procedure View Table


xxxxxxxxxxxxxx
vvvvvvvvvvvvvv vvvvvvvvvvvvvv
xxxxxxxxxxxxxx xxxxxxxxxxxxxx
vvvvvvvvvvvvvv
vvvvvvvvvvvvvv
xxxxxxxxxxxxxx xxxxxxxxxxxxxx
vvvvvvvvvvvvvv
xxxxxxxxxxxxxx
Network vvvvvvvvvvvvvv
xxxxxxxxxxxxxx
vvvvvvvvvvvvvv vvvvvvvvvvvvvv
xxxxxxxxxxxxxx
vvvvvvvvvvvvvv

VALID INVALID INVALID

Local and remote references

Direct local Direct remote Definition


dependency dependency change

Wipro Confidential 266


A
A Scenario
Scenario of
of Local
Local Dependencies
Dependencies

ADD_EMP NEW_EMP view


procedure EMPNO ENAME
xxxxxxxxxxxxxxxxxxxxx 7839 KING
vvvvvvvvvvvvvvvvvvvvv
vvvvvvvvvvvvvvvvv
7698 BLAKE
vvvvvvvvvvvvvvvvvvvvv 7782 CLARK
vvvvvvvvvvvvvvvvvvvvv
vvvvvvxxxxxxxxxxxxxxx 7566 JONES
xxxxxxxxxxxxxxxxxxxxx
vvvvvvvvvvvvvvvvvvvvv

QUERY_EMP EMP table


procedure EMPNO ENAME HIREDATE JOB
xxxxxxxxxxxxxxxxxxxxx
7839 KING 17-NOV-81 PRESIDENT
vvvvvvvvvvvvvvvvvvvvv 7698 BLAKE 01-MAY-81 MANAGER
vvvvvvvvvvvvvvvvv
vvvvvvvvvvvvvvvvvvvvv 7782 CLARK 09-JUN-81 MANAGER
vvvvvvvvvvvvvvvvvvvvv
vvvvvvxxxxxxxxxxxxxxx 7566 JONES 02-APR-81 MANAGER
xxxxxxxxxxxxxxxxxxxxx
vvvvvvvvvvvvvvvvvvvvv

Wipro Confidential 267


Displaying Dependencies
DEPTREE and IDEPTREE views
SQL>
SQL> SELECT
SELECT nested_level,
nested_level, type,
type, name
name
22 FROM
FROM deptree
deptree
33 ORDER
ORDER BYBY seq#;
seq#;
NESTED_LEVEL
NESTED_LEVEL TYPE
TYPE NAME
NAME
------------ --------- ----
------------ --------- ----
00 TABLE
TABLE EMP
EMP
11 VIEW
VIEW NEW_EMP
NEW_EMP
22 PROCEDURE
PROCEDURE ADD_EMP
ADD_EMP
11 PROCEDURE QUERY_EMP
PROCEDURE QUERY_EMP
SQL>
SQL> SELECT
SELECT **
22 FROM
FROM ideptree;
ideptree;
DEPENDENCIES
DEPENDENCIES
---------------------------------------------------
---------------------------------------------------
TABLE
TABLE SCOTT.EMP
SCOTT.EMP
VIEW
VIEW SCOTT.NEW_EMP
SCOTT.NEW_EMP
PROCEDURE
PROCEDURE SCOTT.ADD_EMP
SCOTT.ADD_EMP
PROCEDURE
PROCEDURE SCOTT.QUERY_EMP
SCOTT.QUERY_EMP

Wipro Confidential 268


Another
Another Scenario
Scenario of
of Local
Local Dependencies
Dependencies

xxxxxxxxxxxxxxxxxxxxx
vvvvvvvvvvvvvvvvvvvvv

REDUCE_SAL vvvvvvvvvvvvvvvvv
vvvvvvvvvvvvvvvvvvvvv
vvvvvvvvvvvvvvvvvvvvv
procedure vvvvvvxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxx
vvvvvvvvvvvvvvvvvvvvv

RAISE_SAL
procedure xxxxxxxxxxxxxxxxxxxxx
vvvvvvvvvvvvvvvvvvvvv
vvvvvvvvvvvvvvvvv

EMP table
vvvvvvvvvvvvvvvvvvvvv
vvvvvvvvvvvvvvvvvvvvv
vvvvvvxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxx
vvvvvvvvvvvvvvvvvvvvv
EMPNO ENAME HIREDATE JOB
7839 KING 07-NOV-81 PRESIDENT
7698 BLAKE 01-MAY-81 MANAGER
7782 CLARK 09-JUN-81 MANAGER
7566 JONES 02-APR-81 MANAGER

Wipro Confidential 269


A
A Scenario
Scenario of
of Local
Local Naming
Naming Dependencies
Dependencies

QUERY_EMP EMP public synonym


procedure EMPNO ENAME HIREDATE JOB
xxxxxxxxxxxxxxxxxxxxx
vvvvvvvvvvvvvvvvvvvvv
7839 KING 17-NOV-81 PRESIDENT

X
vvvvvvvvvvvvvvvvv 7698 BLAKE 01-MAY-81 MANAGER
vvvvvvvvvvvvvvvvvvvvv
vvvvvvvvvvvvvvvvvvvvv 7782 CLARK 09-JUN-81 MANAGER
vvvvvvxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxx 7566 JONES 02-APR-81 MANAGER
vvvvvvvvvvvvvvvvvvvvv

EMP
table
EMPNO ENAME HIREDATE JOB
7839 KING 17-NOV-81 PRESIDENT
7698 BLAKE 01-MAY-81 MANAGER
7782 CLARK 09-JUN-81 MANAGER
7566 JONES 02-APR-81 MANAGER

Wipro Confidential 270


Remote Dependencies
Procedure Procedure View Table
xxxxxxxxxxxxxx
vvvvvvvvvvvvvv vvvvvvvvvvvvvv
xxxxxxxxxxxxxx xxxxxxxxxxxxxx
vvvvvvvvvvvvvv
vvvvvvvvvvvvvv
xxxxxxxxxxxxxx xxxxxxxxxxxxxx
vvvvvvvvvvvvvv
xxxxxxxxxxxxxx
Network vvvvvvvvvvvvvv
xxxxxxxxxxxxxx
vvvvvvvvvvvvvv vvvvvvvvvvvvvv
xxxxxxxxxxxxxx
vvvvvvvvvvvvvv

VALID INVALID INVALID

Local and remote references

Direct local Direct remote Definition


dependency dependency change

Wipro Confidential 271


Concepts of Remote Dependencies

Remote dependencies are governed by the mode chosen by the


user:
 TIMESTAMP checking
or
 SIGNATURE checking

Wipro Confidential 272


Remote Dependency Mode Parameter

Setting REMOTE_DEPENDENCIES_MODE
 As an init.ora parameter
 REMOTE_DEPENDENCIES_MODE = value
 At system level
 ALTER SYSTEM SET REMOTE_DEPENDENCIES_MODE = value
 At session level
 ALTER SESSION SET REMOTE_DEPENDENCIES_MODE = value

Wipro Confidential 273


Remote
Remote Dependencies
Dependencies and
and Timestamp
Timestamp Mode:
Mode: Scenario
Scenario

Procedure Procedure View Table


xxxxxxxxxxxxxx
vvvvvvvvvvvvvv
xxxxxxxxxxxxxx
vvvvvvvvvvvvvv vvvvvvvvvvvvvv
xxxxxxxxxxxxxx xxxxxxxxxxxxxx
vvvvvvvvvvvvvv vvvvvvvvvvvvvv
xxxxxxxxxxxxxx
vvvvvvvvvvvvvv
Network xxxxxxxxxxxxxx
vvvvvvvvvvvvvv
xxxxxxxxxxxxxx xxxxxxxxxxxxxx
vvvvvvvvvvvvvv vvvvvvvvvvvvvv

VALID INVALID INVALID

Network Definition
change

Wipro Confidential 274


Remote
Remote Procedure
Procedure B
B Compiled
Compiled at
at 8:00
8:00

Remote procedure B

Compiles
Valid

Wipro Confidential 275


Local
Local Procedure
Procedure A
A Compiles
Compiles at
at 9:00
9:00

Local procedure A Remote procedure B

Timestamp Record Timestamp


of A timestamp of B
of B

Valid Valid

Wipro Confidential 276


Execute
Execute Procedure
Procedure A
A

Local procedure A Remote procedure B

Timestamp
comparison
Timestamp Timestamp Timestamp
of A of B of B
Execute B

Valid Valid

Wipro Confidential 277


Execute
Execute Procedure
Procedure A
A

Local procedure A Remote procedure B

Timestamp
comparison
Timestamp Timestamp Timestamp
of A of B of B
ERROR

Valid Invalid Valid

Wipro Confidential 278


Recompiling a PL/SQL Program Unit

 Handled automatically through implicit runtime recompilation


 Handled through explicit recompilation with the ALTER statement

ALTER
ALTER PROCEDURE
PROCEDURE [SCHEMA.]
[SCHEMA.] procedure_name
procedure_name COMPILE
COMPILE

ALTER
ALTER FUNCTION
FUNCTION [SCHEMA.]
[SCHEMA.] function_name
function_name COMPILE
COMPILE
ALTER
ALTER PACKAGE
PACKAGE [SCHEMA.]
[SCHEMA.] package_name
package_name COMPILE
COMPILE PACKAGE
PACKAGE
ALTER
ALTER PACKAGE
PACKAGE [SCHEMA.]
[SCHEMA.] package_name
package_name COMPILE
COMPILE BODY
BODY

ALTER
ALTER TRIGGER
TRIGGER trigger_name
trigger_name [ENABLE|DISABLE|COMPILE[DEBUG]]
[ENABLE|DISABLE|COMPILE[DEBUG]]

Wipro Confidential 279


Recompilation of Procedures

Recompiling dependent procedures and functions will be


unsuccessful when:
 The referenced object is dropped or renamed
 The datatype of the referenced column is changed
 A referenced view is replaced by a view with different columns
 The parameter list of a referenced procedure is modified

Wipro Confidential 280


Recompilation of Procedures

Recompiling dependent procedures and functions will be


successful if:
 The referenced table has new columns
 The datatype of referenced columns has not changed
 A private table is dropped, but a public table, having the same name
and structure, exists
 The PL/SQL body of a referenced procedure has been modified and
recompiled successfully

Wipro Confidential 281


Recompilation of Procedures

Minimize dependency failures by:


 Declaring records using the %ROWTYPE attribute
 Declaring variables with the %TYPE attribute
 Querying with the SELECT * notation
 Including a column list with INSERT statements

Wipro Confidential 282


Packages
Packages and
and Dependencies
Dependencies

Package specification
Standalone
Procedure A Valid
procedure declaration

Valid
Package body

Procedure A
definition

Definition changed

Wipro Confidential 283


Packages
Packages and
and Dependencies
Dependencies

Package specification

Procedure A Valid
declaration

Package body
Invalid

Standalone Procedure A
definition
procedure

Definition
changed

Wipro Confidential 284


Debugging Using The DBMS_OUTPUT Package

The DBMS_OUTPUT package:

 Accumulates information into a buffer


 Allows retrieval of the information from the buffer

Wipro Confidential 285


How to Use DBMS_OUTPUT

 1. Enable SERVEROUTPUT

SQL>
SQL> SET
SET SERVEROUTPUT
SERVEROUTPUT ON
ON

2.
2. Put
Put text
text into
into the
the buffer
buffer
SQL>
SQL> EXECUTE
EXECUTE DBMS_OUTPUT.PUT
DBMS_OUTPUT.PUT ('testing
('testing 11 22 33 ')
')
PL/SQL
PL/SQL procedure
procedure successfully
successfully completed.
completed
completed.
completed

3.
3. Display
Display from
from the
the buffer
buffer
SQL>
SQL> EXECUTE
EXECUTE DBMS_OUTPUT.NEW_LINE
DBMS_OUTPUT.NEW_LINE
testing
testing 11 22 33
PL/SQL
PL/SQL procedure
procedure successfully
successfully completed.
completed.
or
or put
put text
text into
into the
the buffer
buffer and
and display
display
SQL>
SQL> EXECUTE
EXECUTE DBMS_OUTPUT.PUT_LINE('Another
DBMS_OUTPUT.PUT_LINE('Another test
test 44 55 6')
6')
testing
testing 11 22 33 Another
Another test
test 44 55 66
PL/SQL
PL/SQL procedure
procedure successfully
successfully completed.
completed.

Wipro Confidential 286


Debugging
Debugging Using
Using DBMS_OUTPUT
DBMS_OUTPUT

CREATE OR REPLACE PACKAGE BODY over_pack IS


PROCEDURE add_dept
(v_deptno IN dept.deptno%TYPE,
v_name IN dept.dname%TYPE DEFAULT 'unknown',
v_loc IN dept.loc%TYPE DEFAULT 'unknown') IS
BEGIN
DBMS_OUTPUT.PUT_LINE ('For the no. of args supplied, ');
DBMS_OUTPUT.PUT_LINE ('executing ADD_DEPT procedure');
DBMS_OUTPUT.PUT_LINE ('(Three args-two with defaults)');
INSERT INTO dept
VALUES (v_deptno,v_name,v_loc);
END add_dept;
PROCEDURE add_dept
(v_name IN dept.dname%TYPE DEFAULT 'unknown',
v_loc IN dept.loc%TYPE DEFAULT 'unknown') IS
BEGIN
DBMS_OUTPUT.PUT_LINE ('For the no. of args supplied, ');
DBMS_OUTPUT.PUT_LINE ('executing ADD_DEPT procedure');
DBMS_OUTPUT.PUT_LINE ('(Two args -both with defaults)');
INSERT INTO dept
VALUES (dept_deptno.NEXTVAL,v_name,v_loc);
END add_dept;
END over_pack;

Wipro Confidential 287


Debug Output

Sample output from the previous procedure

SQL> SET SERVEROUTPUT ON


SQL> EXECUTE OVER_PACK.ADD_DEPT('EDUCATION')
For the no. of args supplied,
executing ADD_DEPT procedure
(Two args -both with defaults)

PL/SQL procedure successfully completed.

Wipro Confidential 288


Summary
Summary

USER_SOURCE
System table

Source
code
Compile USER_ERRORS
Compile System table
p-code
errors

Wipro Confidential 289


Summary
Summary

Execute

Debug
information

Wipro Confidential 290


Summary

 Avoid disrupting production by:

 Keeping track of dependent


 proceduresRecompiling procedures manually as soon as
possible after the definition of a database object changes

Wipro Confidential 291


Working with Object Types

Wipro Confidential 292


Objectives

 After completing this lesson, you should be able to do


the following:

 Describe object types


 Create transient objects
 Manipulate objects in object tables

Wipro Confidential 293


An Object Type

 Is a user-defined composite datatype


 Encapsulates a data structure along with the methods needed
to manipulate it

Ship

CheckStatus
Attribute order_no

Cancel
cust_info
line_items
Method amount
Hold

 A transient object is an instance of an object type

Wipro Confidential 294


The Structure of an Object Type

Specification

Public Attribute declarations


interface
Method specifications

Body

Private
implementation
Method bodies

Wipro Confidential 295


Creating an Object Type Specification

Syntax

CREATE
CREATE [OR [OR REPLACE]
REPLACE] TYPE
TYPE type_name
type_name IS|AS
IS|AS OBJECT
OBJECT
(attribute1
(attribute1 datatype,
datatype,
attribute2
attribute2 datatype,
datatype,
.. .. ..
[MEMBER
[MEMBER procedure1|function1
procedure1|function1 spec,
spec,
MEMBER
MEMBER procedure2|function2
procedure2|function2 spec,
spec,
.. .. ..
[PRAGMA
[PRAGMA RESTRICT_REFERENCES
RESTRICT_REFERENCES
(procedure1|function1,
(procedure1|function1, WNDSWNDS [,
[, RNDS,
RNDS, WNPS,
WNPS, RNPS])
RNPS])
.. .. .. ]]
]]
)[;]
)[;]

Wipro Confidential 296


Creating an Object Type Body

Syntax

CREATE
CREATE [OR
[OR REPLACE]
REPLACE] TYPE
TYPE BODY
BODY type_name
type_name IS|AS
IS|AS
[MEMBER
[MEMBER procedure1|function1
procedure1|function1 body,
body,
procedure2|function2
procedure2|function2 body,
body,
.. .. .];
.];

Wipro Confidential 297


Example: Creating an Object Type Specification

SQL> CREATE OR REPLACE TYPE name_typ AS OBJECT


2 (f_name VARCHAR2(25),
3 l_name VARCHAR2(25),
1
4 initials VARCHAR2(7),
5 MEMBER FUNCTION full_name return VARCHAR2,
6 PRAGMA RESTRICT_REFERENCES( full_name, 2
7 WNDS, WNPS, RNPS )
8 );
9 /

Wipro Confidential 298


Example: Creating an Object Type Body

SQL> CREATE OR REPLACE TYPE BODY name_typ AS


2 MEMBER FUNCTION full_name RETURN VARCHAR2
3 IS
4 BEGIN 1
5 RETURN (l_name || ' ' || f_name );
6 END full_name;
7 END;
8 /

Wipro Confidential 299


Example: Creating a Complex Object Type Specification

SQL> CREATE OR REPLACE TYPE emp_typ AS OBJECT


2 (emp_id NUMBER(7),
3 name name_typ, --datatype is object type
4 street VARCHAR2(25),
5 city VARCHAR2(15),
6 state CHAR(2),
7 zip INTEGER,
8 MEMBER FUNCTION get_name RETURN VARCHAR2,
9 PRAGMA RESTRICT_REFERENCES(get_name,
10 WNDS, RNDS, WNPS, RNPS),
11 MEMBER PROCEDURE set_l_name (v_name VARCHAR2)
12 );
13 /

Wipro Confidential 300


Example: Creating a Complex Object Type Body

SQL> CREATE OR REPLACE TYPE BODY emp_typ AS


2 MEMBER FUNCTION get_name RETURN VARCHAR2
3 IS
4 BEGIN
5 RETURN (name.l_name ||' '|| name.f_name );
6 END get_name;
7 MEMBER PROCEDURE set_l_name (v_name VARCHAR2)
8 IS
9 BEGIN
10 name.l_name := v_name;
11 END set_l_name;
12 END;
13 /

Wipro Confidential 301


Data Dictionary Views for Objects and Object Type Methods

 Information about objects, including object types can be


found in:
 USER_OBJECTS
 USER_TYPES

 Information about object type methods can be found in:


 USER_METHOD_PARAMS
 USER_METHOD_RESULTS
 USER_TYPE_METHODS

Wipro Confidential 302


Example: Calling Object Methods

SQL> CREATE TABLE name_table OF name_typ;


SQL> INSERT INTO name_table
2 VALUES('Marilyn','Monroe','MM');
SQL> SELECT nt.f_name,nt.full_name()
2 FROM name_table nt;

Wipro Confidential 303


Using the Constructor Method

SQL> CREATE TYPE tv_type AS OBJECT


2 (tv_category VARCHAR2(20),
3 screen_size NUMBER(4)
4 );
5 /

DECLARE
v_new_tv tv_type := tv_type('WEB tv', 32);
v_alt_tv tv_type;
BEGIN
v_alt_tv := tv_type('Big Screen', 72);
END;

Wipro Confidential 304


Manipulating Objects
Object table with a complex object type
SQL> CREATE TABLE person_tab OF emp_typ;
Table created.
SQL> DESCRIBE person_tab
Name Null? Type
-------------------------- -------- ----
EMP_ID NUMBER(7)
NAME NAME_TYP
STREET VARCHAR2(25)
CITY VARCHAR2(15)
STATE CHAR(2)
ZIP NUMBER(38)
SQL> DESCRIBE name_typ
Name Null? Type
-------------------------- -------- ----
F_NAME VARCHAR2(25)
L_NAME VARCHAR2(25)
INITIALS VARCHAR2(7)
METHOD
------
MEMBER FUNCTION FULL_NAME RETURNS VARCHAR2

Wipro Confidential 305


Manipulating Objects: Inserting

Adding objects to an object table:

SQL> INSERT INTO name_table


2 VALUES ('John','Nike','JN')

Using the constructors for the complex object type table:


SQL> INSERT INTO person_tab
2 VALUES (1235,
3 NAME_TYP('Ellen','Gravina','EG'),
4 '1 Avocet Drive','Redwood Shores','CA',94065);

SQL> INSERT INTO person_tab


2 VALUES ( EMP_TYP(1236,
3 NAME_TYP('Christian','Bauwens','CB'),
4 '2 Avocet Drive','Redwood Shores','CA',94065) );

Wipro Confidential 306


Manipulating Objects: Selecting

To return a result set of rows:


SQL> SELECT *
2 FROM name_table;

SQL> SELECT *
2 FROM person_tab;

SQL> SELECT *
2 FROM person_tab p
3 WHERE p.name.f_name like '%ll%';

To return a result set of objects:


SQL> SELECT VALUE(p)
2 FROM person_tab p;

Wipro Confidential 307


Manipulating Objects: Updating

Updating attributes of an object table:


SQL> UPDATE person_tab p
2 SET p.street = '25 Elk Street'
3 WHERE p.emp_id = 1235;

Using the constructor for the object type:


SQL> UPDATE name_table nt
2 SET nt = name_typ('Charlie','Brown','CB')
3 WHERE nt.l_name = 'Nike'

Wipro Confidential 308


Manipulating Objects: Deleting

Removing objects from an object table:

SQL> DELETE FROM name_table nt


2 WHERE nt.initials = 'MM';

SQL> DELETE FROM person_tab p


2 WHERE p.name.initials = 'CB';

Wipro Confidential 309


Summary

 Object types give developers the ability to construct


data types that were not previously defined.

 An object type has three components:


 Attribute specification
 Method specification
 Method implementation

 Object types can be simple or complex.

Wipro Confidential 310


Assignment
Assignment

Wipro Confidential
Thank you

You might also like