Académique Documents
Professionnel Documents
Culture Documents
ORACLE 9i
PL/SQL
By System Consultant
System Consultant
2
Table of Contents
Serial No.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Topic Name
Programming Basics
PLSQL Records
Cursors
PLSQL Tables
Exceptions
Procedures
Functions
Oracle Supplied Packages
Packages
Ref Cursors
Types
Varrays
Nested Table
Bfile and LOBs
Triggers
Assignments
Page No.
3
21
25
34
41
49
61
66
79
94
96
99
105
111
118
133
System Consultant
3
Declaration Part
optional part where variables are defined
Executable Part
System Consultant
mandatory part which consists of executable statements
Exception Handling Part
optional part which consists of code for handling errors (runtime)
Pl/SQL Files -
PL/SQL programs can be written in any editor and saved as files with .sql
extension
Can also use ED command in SQL*Plus to create a PL/SQL program file
Use the @ <filename> command to execute a PL/SQL program file
o Variables - Used to store results of a query for later processing, or to calculate values to be
inserted into database tables
Can be used anywhere in an expression, either in SQL or PL/SQL statements
Must be declared before referencing it in other statements, including other
declarative statements
Are declared by specifying the name along with the datatype
Can be declared to be of any datatype native to Oracle
Examples
oldfare NUMBER(5);
m_name VARCHAR(15);
(Note Set Serveroutput On has to be given when a session starts for displaying the
output statements_)
declare
x number;
begin
x := 67;
dbms_output.put_line(x);
dbms_output.put_line('The value of x is '|| x);
end;
Declaring variable in declare block.
Assigning value in in begin block using := .
Output statement is dbms_output.put_line
Concatenation operator is ||
Command terminator is ; after end
Declaring and initializing variables together
declare
y number := 100;
begin
dbms_output.put_line('The value of y is '|| y);
end;
-------------------------------------------------------------------------------
System Consultant
5
System Consultant
6
System Consultant
7
Example
emp_rec employee%ROWTYPE;
A specific field can be referenced using
emp_rec.emp_num;
declare
E emp%rowtype;
/*rowtype attribute holds the datatype of the columns of the
entire row*/
begin
select * INTO E
from emp
where ename = 'MARTIN';
dbms_output.put_line(E.sal);
dbms_output.put_line(E.ename);
dbms_output.put_line(e.deptno);
end;
Conditional Statements IF
The selection structure tests a condition, then executes one sequence of statements
instead of another, depending on the condition
There are three forms of statements
IF-THEN
IF-THEN-ELSE
IF-THEN-ELSIF
Sequence of statements is executed only if the condition evaluates to TRUE
If condition evaluates to FALSE or NULL, it does nothing
In either case control passes to next statement after the IF-THEN structure
IF <condition> THEN
statements;
END IF;
Sequence of statements in the ELSE clause is executed only if the condition
evaluates to FALSE or NULL
IF <condition> THEN
statements;
ELSE
statements;
END IF;
-------------------------------------------------------------------------------declare
/*Simple if condition */
x number;
begin
x := &x;
if x >= 35 then
System Consultant
8
dbms_output.put_line('Passed');
else
dbms_output.put_line('Failed');
end if;
end;
----------------------------------------------------IF-THEN-ELSIF Structure
This construct allows selection of action from several mutually exclusive
alternatives
The IF statement can have any number of ELSIF clauses
The final ELSE is optional
Conditions are evaluated one by one from top to bottom
Syntax
IF <condition1> THEN
statements;
ELSIF <condition2> THEN
statements;
ELSIF <condition3> THEN
statements;
ELSE
statements;
END IF;
Example 1
Declare
y number;
/*Multiple ifs */
Begin
y := &y;
if y >= 70 then
dbms_output.put_line('Distinction');
elsif y >= 60 then
dbms_output.put_line('First class');
elsif y >= 50 then
dbms_output.put_line('Second class');
elsif y >= 35 then
dbms_output.put_line('Passed');
else
dbms_output.put_line('Failed');
end if;
end;
Example 2
System Consultant
9
Declare
n adm.name%type;
m adm.marks%type;
c adm.college%type;
f adm.fees%type;
Begin
n := '&n';
m := &m;
if m >= 95 then
c := 'COEP';
f := 10000;
elsif m >= 90 then
c := 'MIT';
f := 15000;
elsif m >= 85 then
c := 'VIT';
f := 22000;
elsif m >= 80 then
c := 'D Y Patil';
f := 27000;
elsif m >= 75 then
c := 'Pune Vidyarthi';
f := 33000;
else
dbms_output.put_line('Cannot get admission');
end if;
if c is not null and f is not null then
dbms_output.put_line('Your College is '|| c || ' and fees are ' || f);
Insert into adm
System Consultant
10
values(n,m,c,f);
commit;
end if;
end;
Nested Blocks
declare
x number;
begin
x := 80;
dbms_output.put_line(abc);
declare
y number;
begin
y := 90;
dbms_output.put_line('Inner Block variable value ' || y);
end;
dbms_output.put_line('Outer Block variable value ' || x);
end;
Scope of variables
A variable declared in the outer block is accessible in the inner block. But a variable
declared in the inner block is accessible only in the inner block.
declare
outer number;
begin
outer := 80;
declare
inner number;
begin
inner := 90;
dbms_output.put_line('Inner Block variable value ' || inner);
dbms_output.put_line('Outer block variable is accessible in the inner
block);
dbms_output.put_line('Outer block variable value ' || outer);
end;
dbms_output.put_line('Outer Block variable value ' || outer);
System Consultant
11
System Consultant
12
System Consultant
13
FOR LOOP
Advantages -1) No need of declaring loop variable
2) No need of giving condition
3) No need of updation statement (increment or decrement )
4)Code becomes small and compact
Disadvantage -Updation can be done by only one.
Syntax
FOR <counter> IN [REVERSE]
lower_bound .. higher_bound LOOP
statements;
END LOOP
Example 1 of for loop
/*To show 1 to 10 on screen*/
begin
for x in 1..10
Loop
dbms_output.put_line(x);
End Loop;
end;
Example 2
/*Reverse for loop 10,9,8 1*/
Begin
for i in REVERSE 1 ..10
Loop
dbms_output.put_line(i);
End Loop;
end;
Example 3
Calculating compound interest for a principal of Rs.100 @10% for each year.
Values will be shown of the CI after each year.
create table CI_100
(year number(2),
System Consultant
14
total number(4));
---------------------------------Declare
p number := 100;
tot number;
/*Calculation of compound interest.
Rs.100 is principal.
Rate of interest is 10%.
Period is 5 years.
*/
Begin
for y in 1..5
Loop
/* Tot variable is getting 10% more than p */
tot := p + p * 0.10;
Insert into CI_100
values(y,tot);
/*Since the next interest is based on the current interest
so the tot will be considered as p for the next year*/
p := tot;
End Loop;
end;
WHILE-LOOP Statement
Associates a condition with a sequence of statements enclosed within LOOP-END
LOOP
Condition evaluated before each iteration
If condition evaluates to TRUE, sequence of statements is executed and control
resumes at the top of the loop
If condition evaluates to FALSE or NULL, loop is bypassed and control passes to
next statement
Number of iterations depends on the condition and is unknown until the loop
completes
WHILE <condition>
LOOP
statements;
END LOOP;
System Consultant
15
System Consultant
16
Basic Loop
Declare
x number;
Begin
x := 1;
Loop
dbms_output.put_line(x);
exit when x = 1;
x := x + 1;
End Loop;
dbms_output.put_line('End of program');
End;
/
The loop gets executed at least once.
Nested Loops
create table discount_details
(quarter number(2),
month number(2),
discount varchar2(5));
Expected Output
QUARTER
1
1
1
2
2
2
3
3
3
4
4
4
MONTH
1
2
3
4
5
6
7
8
9
10
11
12
12 rows selected.
DISCOUNT
12%
11%
10%
9%
8%
7%
6%
5%
4%
3%
2%
1%
System Consultant
17
declare
q number;
m number;
d number;
dis varchar2(10);
c number;
begin
q := 1;
m := 0;
d := 12;
loop
exit when q > 4;
c := 0;
loop
exit when c >= 3;
m := m + 1;
dis := d || '%';
insert into discount_details
values(q,m,dis);
d := d - 1;
c := c + 1;
end loop;
q := q + 1;
end loop;
end;
GOTO Statement
Branches to a label unconditionally
When executed, it changes the flow of control in a PL/SQL block
Two parts needed to code a GOTO statement
Define a label name
Use the GOTO statement to pass control to the label
Label name
optionally used to name a PL/SQL block or statements within the block
Defined using angular brackets (<< >>)
<<if_fare_label>>
IF condition THEN
statements;
END IF;
statements;
GOTO if_fare_label;
Transfer of control using GOTO statement is allowed in the following places
System Consultant
from a block to an executable statement
branch from an exception handler into an enclosing block
Transfer of control using GOTO statement is NOT allowed in the following
places
from within one IF statement or loop clause to another
from an enclosing block into a sub-block
from an exception handler into the current block
out of a subprogram
to keywords
Examples of GOTO
1) create table prec
(name varchar2(20),
dept varchar2(20));
create table mahrec
(name varchar2(20),
dept varchar2(20),
city varchar2(30));
/*Pune records should go in both the tables prec and mahrec.
Any other city record should go in mahrec table only.*/
declare
n prec.name%type;
d prec.dept%type;
c mahrec.city%type;
begin
n := '&n';
d := '&d';
c := '&c';
if c = 'Pune' then
goto s1;
else
goto s2;
end if;
<<s1>>
Insert into prec
values(n,d);
<<s2>>
Insert into mahrec
values(n,d,c);
18
System Consultant
19
end;
Wrong usage of goto
declare
x number;
begin
x := 90;
<<s1>>
dbms_output.put_line('S1');
if x = 90 then
dbms_output.put_line('Condition is true');
goto s1;
else
dbms_output.put_line('Condition is false');
end if;
end;
/
PL/SQL Records
Objects of type RECORD are called PL/SQL records
PL/SQL records have uniquely named fields, which can belong to different
datatypes
Define a RECORD type
TYPE <typename> IS RECORD
(fieldname1 <fieldtype>
:
fieldnameN <fieldtype> ;
(%TYPE and %ROWTYPE can be used to specify <fieldtype>]
Example 1 of Record Type
Declare
TYPE empdetails IS RECORD
(eno Emp.Empno%type,
name Emp.Ename%type,
s Emp.Sal%type);
VE empdetails;
Begin
Select empno,ename,sal Into VE
from Emp
where ename = 'SMITH';
System Consultant
20
System Consultant
21
End;
-------------------------------------
System Consultant
22
Cursors
To process a SQL statement, PL/SQL opens a work area called a context area.
PL/SQL uses this area to execute SQL statements and store processing
information
A PL/SQL construct called Cursor allows you to name a context area, access its
information and in some cases, control its processing
Explicit Cursors
Defined by the user to keep track of which row is being processed, when a query returns
multiple rows
Defining a Cursor
A cursor is defined in the declarative part of the PL/SQL block by naming it and
associating it with a query
CURSOR <cursorname> IS
<SELECT statement>;
Example
CURSOR emp_cur IS
SELECT empno, ename, job, sal
FROM emp;
A Cursor can be manipulated using
OPEN
System Consultant
FETCH
CLOSE
Cursor must be declared before it can be referenced using the OPEN, CLOSE or
FETCH statements
The OPEN Statement
Initializes or opens a cursor
Cursor must be opened before any rows are returned by the query
OPEN <cursorname>
Example -OPEN emp_cur;
The FETCH Statement
Can be executed repeatedly until all rows have been retrieved
FETCH <cursorname> INTO var1, , varN;
OR
FETCH <cursorname> INTO record_variable;
Example
FETCH emp_cur INTO mrec;
The CLOSE Statement
Closes the cursor and makes the active set undefined
CLOSE <cursorname>;
Example
CLOSE emp_cur;
Once a cursor is closed, it can be reopened by using the OPEN statement
Attributes of Explicit Cursors
Every cursor has four attributes that can be used to access the cursors context
area
%NOTFOUND
%FOUND
%ROWCOUNT
%ISOPEN
To use these attributes, simple append them to the name of the cursor
%NOTFOUND
evaluates to TRUE if last FETCH failed because no more rows were
available
evaluates to FALSE if last FETCH returned a row
%FOUND
evaluates to TRUE if last FETCH returned a row
23
System Consultant
24
System Consultant
25
select *
from emp
where job ='&J';
M cf%rowtype;
N number;
J Emp.Job%type;
Begin
Open cf;
N := 0;
Loop
Fetch cf into M;
Exit when cf%notfound;
If cf%found then
N := N + 1;
End if;
End Loop;
Close cf;
If N > 0 then
dbms_output.put_line('Total number of job ' || J || ' is '|| N);
else
dbms_output.put_line('No such job');
End If;
End;
---------------------------------------------------------------------3) Use of IsOpen attribute
Declare
Cursor cf is
select ename, deptno
from emp
where deptno = 20;
M cf%rowtype;
/*The cursor is not opened before Loop. So using IsOpen attribute to open the
cursor if it is not open.*/
Begin
/* Cursor is not opened!!! */
Loop
If cf%IsOpen then
Fetch cf into M;
System Consultant
26
else
Open cf;
dbms_output.put_line('Cursor is now opened');
End if;
exit when cf%notfound;
dbms_output.put_line(M.ename ||'--' || M.deptno);
End Loop;
End;
-------------------------------------------------------------------------------------4) Transferring the first five records from emp table into another table FirstFive
create table firstfive
as
select empno,ename,sal,deptno
from emp
where 1=2;
Declare
Cursor cf is
Select *
from emp;
M cf%rowtype;
N number;
Begin
Open cf;
N := 1;
while N <= 5
Loop
Fetch cf into M;
Insert into firstfive
values(M.empno,M.ename,M.sal,M.deptno);
N := N +1;
End Loop;
End;
5) Displaying the 3rd record entered in the table emp
Declare
Cursor cf is
select *
from emp;
M cf%rowtype;
Begin
Open cf;
Loop
System Consultant
27
fetch cf into M;
if cf%rowcount = 3 then
dbms_output.put_line(M.empno||'-'||M.ename||'-'||M.sal||'-'||M.deptno);
end if;
exit when cf%notfound;
End Loop;
End;
6) To see the first person( or first record entered) who has got salary > 2800
Declare
Cursor cf is
select *
from emp
where sal > 2800;
M cf%rowtype;
Begin
Open cf;
Loop
fetch cf into M;
if cf%rowcount = 1 then
dbms_output.put_line(M.empno||'-'||M.ename||'-'||M.sal||'-'||M.deptno);
exit;
end if;
End Loop;
End;
Cursor FOR Loop
Implicitly declares its loop index as a record of %ROWTYPE,
Implicitly opens the cursor
Repeatedly fetches rows of values from the active set into fields in the record
Implicitly closes the cursor when all rows have been processed or the loop is
exited
The statements in the loop construct are executed once for each row that satisfies
the query associated with the cursor name
Cursor FOR loop is used to simplify coding
No need of -1)Open cursor
2)Fetch
3)Exit
4)Close cursor
7) To show records where salary is > 3000
Declare
System Consultant
28
Cursor cf is
select *
from emp
where sal >= 3000;
Begin
For mrec in cf
Loop
dbms_output.put_line(mrec.ename||' '||mrec.sal||' '||mrec.deptno);
End Loop;
End;
For Loops using sub queries
No need of declaring cursor.
A private cursor within an anonymous block can be created.
To show names of employees who have job MANAGER.
begin
for MREC in (select * from emp)
Loop
if MREC.job = 'MANAGER' then
dbms_output.put_line('Name is ' ||MREC.ename);
end if;
END LOOP;
end;
Parameterized Cursor
The same cursor can be reopened and closed with different active sets.
declare
cursor cf(pjob emp.job%type)
is
select empno,ename,job,sal
from emp
where job = pjob;
M cf%rowtype;
begin
open cf('ANALYST');
LOOP
FETCH CF INTO M;
EXIT WHEN CF%NOTFOUND;
dbms_output.put_line(M.ename);
end loop;
close cf;
System Consultant
29
open cf('CLERK');
LOOP
FETCH CF INTO M;
EXIT WHEN CF%NOTFOUND;
dbms_output.put_line(M.ename);
end loop;
close cf;
open cf(MANAGER);
LOOP
FETCH CF INTO M;
EXIT WHEN CF%NOTFOUND;
dbms_output.put_line(M.ename);
end loop;
close cf;
END;
System Consultant
30
System Consultant
31
Implicit Cursors
Automatically defined and opened, by Oracle, to process each
SQL statement
most recently opened context area is referred to as a SQL%
cursor
System Consultant
32
System Consultant
33
PL/SQL Tables
Features of PL/SQL tables are as follows
1) It is a composite data type.
2) They are modeled as similar to database tables, but they are not permanent tables.
So they can be created and manipulated only in a PL SQL block.
3) They can have only one column but any data type
4) It will have a primary key which is compulsory for the reference of values
5) There is no name to the column and primary key
6) The data type of the primary key is BINARY_INTEGER.
System Consultant
34
System Consultant
35
i := i + 1;
End Loop;
Close cf;
/*Now retrieving the names from the vname plsql table using for loop.*/
For n in 1..vrows
Loop
dbms_output.put_line('Name is '||vname(n));
End Loop;
End;
System Consultant
36
end if;
dbms_output.put_line('The total number of elements in d are '|| d.count);
/*dbms_output.put_line('The first index number is ' || d.FIRST);
dbms_output.put_line('The last index number is ' || d.LAST);
dbms_output.put_line('The index number after 2 is ' || d.next(2));
dbms_output.put_line('The index number before 8 is ' || d.prior(8));
d.delete(5);
dbms_output.put_line('The total number of elements in d are '|| d.count);
d.delete(11,14);
dbms_output.put_line('The total number of elements in d are '|| d.count);
d.delete;
dbms_output.put_line('The total number of elements in d are '|| d.count); */
end;
System Consultant
37
EXCEPTIONS
Introduction to Exceptions
An error condition is called an Exception
When an error occurs, an exception is raised i.e. normal execution stops and
control transfers to the exception handling part of the PL/SQL block or
subprogram
To handle raised exceptions, separate routines called exception handlers are
written
There are two types of exceptions
Pre-defined exceptions (Internal Exceptions)
User-defined exceptions
You cannot declare an exception twice in the same block, but can declare the
same exception in two different blocks
Exceptions declared in a block are local to that block and global to all its subblocks
Enclosing blocks cannot reference exceptions declared in a sub-block because
blocks can only reference local or global exceptions
Predefined Exceptions
Are implicitly raised whenever a PL/SQL block violates an Oracle rule or exceeds
a system-dependent limit
Every Oracle error has a number, but exceptions must be handled by name
PL/SQL predefines some common Oracle errors as exceptions
These predefined exceptions are declared globally by PL/SQL
Some Pre-defined Exceptions
CURSOR_ALREADY_OPEN
NO_DATA_FOUND
TOO_MANY_ROWS
VALUE_ERROR
ZERO_DIVIDE
More than one exception can be handled in a single exception handler by
separating them with the keyword OR
EXCEPTION
WHEN NO_DATA_FOUND OR TOO_MANY_ROWS THEN
statements;
WHEN OTHERS THEN
statements;
END;
System Consultant
38
System Consultant
39
Exception
When ZERO_DIVIDE then
dbms_output.put_line('Cannot divide by zero!!!');
end;
4) DUP_VAL_ON_INDEX error (When a duplicate value is entered in a column
having Unique constraint)
declare
e emp.empno%type;
begin
e := &e;
insert into emp (empno )
values(e);
dbms_output.put_line('Successful');
Exception
When DUP_VAL_ON_INDEX then
dbms_output.put_line('Value already exists');
end;
5) VALUE_ERROR (Error in conversion of string to number)
declare
n number;
begin
n := '&n';
dbms_output.put_line(n);
Exception
When VALUE_ERROR then
dbms_output.put_line('Please enter number only');
end;
6) OTHERS (If no error handler works then at least OTHERS will work)
declare
x number;
y number;
z number;
begin
x := &x;
y := &y;
z := x/y;
dbms_output.put_line('The answer is ' || z);
System Consultant
40
Exception
When too_many_rows then
dbms_output.put_line('More than one value');
When no_data_found then
dbms_output.put_line('No value');
/*When OTHERS then
dbms_output.put_line('Some run time error has occurred');
dbms_output.put_line('Please execute the program again with proper values.');
rollback;*/
end;
Pragma Exception
create table dept1(deptno number primary key, dname varchar2(10));
create table emp1(empno number, ename varchar2(10),
deptno number references dept1(deptno));
insert into dept1 values(10,'Acc');
insert into emp1 values(1,'abc',10);
System Consultant
41
Exception Handlers in nested block to continue after run time error comes
declare
loan_amt number;
no_of_months number;
installment_rate number;
roi number;
tot_amt number;
begin
loan_amt := &loan_amt;
no_of_months := & no_of_months;
begin
installment_rate := loan_amt / no_of_months;
exception
when zero_divide then
no_of_months := 3;
installment_rate := loan_amt / no_of_months;
end;
/* In any case the last 3 lines will get executed */
roi := installment_rate * 0.2; -- 20% roi
tot_amt := roi + loan_amt;
dbms_output.put_line('The total amount to be paid is '|| tot_amt);
end;
System Consultant
42
User-defined Exceptions
User-defined exceptions need to be defined in the declarative part of a PL/SQL
block, subprogram or database trigger
Declared by naming the exception and defining it as datatype EXCEPTION
Example
DECLARE
past_due EXCEPTION;
zero_error EXCEPTION;
Like variables, user-defined exceptions must be given names
Unlike variables, user-defined exceptions cannot be assigned values and cannot be
used in SQL statements
They need to be raised explicitly using the RAISE statement
A block should RAISE an exception only when an error makes it impossible or
impractical to finish processing
RAISE statement for a given expression can be coded anywhere within the scope
of that expression
IF mrec.ss_fare <= 0 THEN
RAISE zero_error;
END IF;
An exception raised inside a handler immediately propagates to the enclosing
block, which is searched to find a handler for the newly raised exception
From there on, the exception propagates normally
To re-raise an exception place a RAISE statement in its local handler
System Consultant
43
System Consultant
44
end if;
end;
--------------------------------------------------------------------------------------------------Example of Raise_application_error and error handling together
declare
x number;
begin
x := '&x';
if x < 0 then
raise_application_error(-20009,'ty');
end if;
exception
when value_error then
dbms_output.put_line('ff');
end;
System Consultant
45
PROCEDURES
Advantages of Subprograms
Provide Extensibility
PL/SQL language can be tailored to suit the needs of the application
Promote reusability and maintainability
Once validated, they can be used with confidence in any number of
applications
Simplifies maintenance/enhancement, as subprogram is only affected if
definition changes
Provide Modularity
Program can be broken down into manageable, well-defined logical
modules
Supports top-down design and stepwise refinement approach to problem
solving
Aid in abstraction
Allow mental separation from particulars
Stubs allow programmers to defer definition of procedures/functions until
main program is tested and debugged
System Consultant
46
exception handlers]
END [<procedurename>];
parameter stands for
variablename [IN|OUT|IN OUT] datatype [{:= | DEFAULT} value]
When a procedure is created, Oracle automatically performs these steps
Compiles the procedure
Stores the compiled code
Stores the procedure in the database
The PL/SQL compiler used to compile the code
If an error occurs, the procedure is created but it is invalid
Enforce Data Security
Can grant users access to a procedure that queries a table, but not
grant access to the table itself
Improve Database Performance
Less amount of information sent over network
Compilation not required to execute code
Procedure present in shared pool so retrieval from disk not required
Memory Savings
Only one copy of procedure needs to be loaded in memory for
execution by multiple users
Increase in Development Productivity
Can avoid redundant coding and increase productivity, by writing a
single procedure
Integrity
Procedures need to be tested only once, to guarantee that it returns
accurate results
Calling a Stored Procedure
Can call a procedure in a PL/SQL statement
Example
branch_sum(NYK);
Can call a procedure from SQL*Plus
Example
SQL> EXECUTE branch_sum(NYK);
System Consultant
47
Examples of Procedures
1) --Procedure without parameters
create or replace procedure pr1
as
s emp.sal%type;
Begin
select sal into s
from emp
where ename = 'SMITH';
dbms_output.put_line(s);
end;
Parameter Modes for Procedures and Functions
Used to define the behavior of formal parameters
Can be used with any subprogram
Three parameter modes
IN (Default)
OUT
IN OUT
IN
allows values to be passed to the subprogram being called
inside the subprogram it acts like a constant
actual corresponding parameter can be a constant, literal, initialized
variable or expression
can be initialized to default values
2) --Supplying parameters to a procedure which are by default of IN type
create or replace procedure pr2(En IN Emp.Empno%type, Name IN Emp.ename
%type,
S Emp.Sal%type)
is
Begin
Insert into Emp(empno,ename,sal)
Values(En,Name,S);
dbms_output.put_line('One record inserted through procedure');
End;
System Consultant
48
System Consultant
49
OUT parameter
allows values to be returned to the caller of a subprogram
inside the subprogram it acts like an uninitialized variable
actual corresponding parameter must be a variable; it cannot be a
constant or expression
its value cannot be assigned to another variable or reassigned to itself
5)
create or replace procedure pr5(Name IN varchar2, Salary OUT number)
Is
Begin
Select sal into Salary
from emp
where ename = Name;
End;
--Steps for displaying the OUT parameter
--1) Compiling the procedure.
--2) Declare the bind variable on SQL prompt as variable payment number
-- Bind variables are of SQL* plus environment which are used to hold the return
--value given by the procedure or function.
--3)Now execute the proc -- exec pr5('SMITH', :payment)
--4)To display the value of payment -- print payment
--5)Bind variables are session specific.Their existence is removed as the session --ends.
System Consultant
50
Using local variable for out parameter when procedure is called inside another
block.
create or replace procedure p1(n in emp.ename%type, s out emp.sal%type)
is
begin
select sal into s
from emp
where ename = n;
end;
declare
x emp.sal%type;
begin
p1('SMITH',x);
dbms_output.put_line(x);
end;
6) IN OUT parameter
allows initial values to be passed and returns updated values to the
caller
inside the subprogram it acts like an initialized variable
actual corresponding parameter must be a variable; it cannot be a
constant or expression
can be assigned a value and its value can be assigned to another
variable
a) create or replace procedure pr6(x IN OUT number)
Is
Begin
x := (x * x);
End;
/*pr6 procedure cannot be executed independently on sql prompt.
System Consultant
51
It has to be called inside a plsql block. It actually gives the square value to the
variable of that plsql block.
In short IN OUT type of paramter makes a procedure similar to function, as the
function also returns the value to the calling environment.*/
b)
declare
a number;
Begin
a := &a;
pr6(a);
/*When a is given as a parameter , it's status is of IN OUT. So IN means the user
input value and OUT means the changes square figure due to the procedure pr6.
After the procedure is called with a as parameter then a value gets changed. At this
time a acts as a OUT parameter, since the procedure is giving the changed value to
a.*/
dbms_output.put_line(a);
End;
System Consultant
52
System Consultant
53
System Consultant
54
System Consultant
55
System Consultant
56
System Consultant
57
Functions
Syntax
CREATE [OR REPLACE] FUNCTION <functionname> [(argument1, argumentN)]
RETURN datatype IS
[local declarations]
BEGIN
executable statements;
[EXCEPTION
exception handlers]
END [<functionname>];
argument stands for
variablename [IN|OUT|IN OUT] datatype [{:= | DEFAULT} value]
Format
CREATE FUNCTION day_fn(mday NUMBER) RETURN CHAR IS
disp_day CHAR(15);
BEGIN
executable statements;
RETURN disp_day;
EXCEPTION
statements;
END day_fn;
Calling a Function
Can call a function as a PL/SQL statement
Example
System Consultant
58
chardays := day_fn(3);
Can call a function as part of an expression
Example
IF day_fn(3) = TUESDAY THEN
statements;
END IF;
The RETURN Statement
Immediately completes execution of subprogram and returns control to caller
In procedures
cannot contain an expression
returns control to the caller before normal end of procedure is reached
In functions
must contain an expression, evaluated when it is executed
Examples of Functions
1)
a)
create or replace function eo ( n number)
RETURN char
is
disp char(30);
Begin
If Mod(n,2) = 0 Then
disp := 'Number is even';
else
disp := 'Number is odd';
End If;
dbms_output.put_line(disp);
RETURN disp;
End;
Select eo(9) from dual;
OR
System Consultant
59
Declare
x number;
y char(30);
Begin
x := &x;
/*Calling the function eo, supplying the parameter x and giving the value to y*/
y := eo(x);
end;
2) Database example
a) create or replace function Remarks ( x number)
RETURN char is
disp char(30);
Begin
If x >= 70 Then
disp := 'Distinction';
Elsif x >= 60 Then
disp := 'First Class';
Elsif x >= 50 Then
disp := 'Second Class';
Elsif x >= 35 Then
disp := 'Passed';
Else
disp := 'Failed';
End If;
RETURN disp;
End;
c) Using this function to insert values for a column of a table
create table st
System Consultant
60
(name varchar2(10),
marks number,
result char(30));
Directly calling the function inside Insert statement
Insert into st
values(John, 90, Remarks(90)); -- Directly calling the function in the values
clause
b) Calling a function in select statement
create or replace function raise_sal(s number)
return number is
begin
return s + 8000;
end;
Select ename,deptno,job,sal, raise_sal(sal)
From emp;
create or replace function f1(s number)
return number
is
begin
delete from emp;
return 0;
end;
Wrong usage of functions
select ename,sal,f1(sal) from emp;
3) Returning more than one value using OUT parameter
a)
create or replace function getdetails(no number,name OUT varchar2)
RETURN varchar2 as
vloc varchar2(30);
begin
select dname,loc into name,vloc
from dept
where deptno = no;
RETURN vloc;
End;
b)
System Consultant
61
System Consultant
62
System Consultant
63
DBMS_SQL Package
What Is Dynamic SQL?
Dynamic SQL enables you to write programs those reference SQL statements whose
full text is not known until runtime. Before discussing dynamic SQL in detail, a clear
definition of static SQL may provide a good starting point for understanding dynamic
SQL. Static SQL statements do not change from execution to execution. The full text of
static SQL statements are known at compilation, which provides the following benefits:
Successful compilation verifies that the SQL statements reference valid database
objects.
Successful compilation verifies that the necessary privileges are in place to access
the database objects.
Performance of static SQL is generally better than dynamic SQL.
Because of these advantages, you should use dynamic SQL only if you cannot use static
SQL to accomplish your goals, or if using static SQL is cumbersome compared to
dynamic SQL. However, static SQL has limitations that can be overcome with dynamic
SQL. You may not always know the full text of the SQL statements that must be executed
in a PL/SQL procedure. Your program may accept user input that defines the SQL
statements to execute, or your program may need to complete some processing work to
determine the correct course of action. In such cases, you should use dynamic SQL.
For example, a reporting application in a data warehouse environment might not know
the exact table name until runtime. These tables might be named according to the starting
month and year of the quarter, for example INV_01_1997, INV_04_1997, INV_07_1997,
INV_10_1997, INV_01_1998, and so on. You can use dynamic SQL in your reporting
application to specify the table name at runtime.
You might also want to run a complex query with a user-selectable sort order. Instead of
coding the query twice, with different ORDER BY clauses, you can construct the query
dynamically to include a specified ORDER BY clause.
Dynamic SQL programs can handle changes in data definitions, without the need to
recompile. This makes dynamic SQL much more flexible than static SQL. Dynamic SQL
lets you write reusable code because the SQL can be easily adapted for different
environments.
Dynamic SQL also lets you execute data definition language (DDL) statements and
other SQL statements that are not supported in purely static SQL programs.
System Consultant
64
Data definition language (DDL) statements, such as CREATE, DROP, GRANT, and
REVOKE
Session control language (SCL) statements, such as ALTER SESSION and SET ROLE
Applications that allow users to input or choose query search or sorting criteria at
runtime
Applications that allow users to input or choose optimizer hints at run time
Applications that query a database where the data definitions of tables are
constantly changing
Applications that query a database where new tables are created often
System Consultant
65
DBMS_SQL is used to write dynamic SQL in stored procedure and to parse DDL
statements.
Some Procedures and Functions in DBMS_SQL package are
Open_Cursor Opens a new cursor and assigns a cursor ID number.
PARSE Parses the DDL or DML statements, i.e. it checks the syntax and associates it
with the opened cursor. In case of DDL statements they are executed immediately after
parsing.
PARSE (ID number of the cursor, DDL or DML statement, language_flag)
language_flag
V7
EXECUTE Executes the SQL statement and returns the number of rows processed.
Especially suitable for keeping track of count of rows affected by a DML statement.
System Consultant
66
System Consultant
67
DBMS_DDL Package
Scenario of recompilation for a procedure
drop table tx1;
create table tx1(a number);
insert into tx1 values(1);
create or replace procedure px1
is
s number;
begin
select a into s
from tx1;
end;
select status from user_objects
where object_name='PX1';
alter table tx1
add b number
select status from user_objects
where object_name='PX1';
alter procedure px1 compile;
select status from user_objects
where object_name='PX1';
OR
Exec px1;
System Consultant
68
System Consultant
69
DBMS_JOB Package
Enables the scheduling and execution of PL/SQL programs.
Submit is the procedure of DBMS_JOB package.
The parameters of Submit procedure are --JOB Unique identifier of the job (Out parameter)
WHAT PL/SQL code to execute as a job
NEXT_DATE Next execution date of the job
INTERVAL Date function to compute the next execution date of a job.
Example
Every next day a new record should get added in the table djt1.
System Consultant
70
Imp setting
System Consultant
71
UTL_FILE Package
UTL_FILE package is used to write data to operating system files such as
text files, word files, excel files, etc.
The data from the oracle table is transferred to the o.s. files. So we can
generate a report of Oracle data in a non-oracle format.
Members of UTL_FILE Package are as follows
FOPEN function
This function opens a file for input or output. The file location must be an
accessible directory, as defined in the instance's initialization parameter
UTL_FILE_DIR. The complete directory path must already exist; it is not
created by FOPEN.
It takes 3 parameters
1. Directory name The path
2. File name (.txt, .doc,.xls,)
3. Open_Mode
a. r Read Text
b. w-- Write Text
c. a Append Text
PUTF procedure
Substitute this sequence with the string value of the next argument in the argument list.
\n
System Consultant
72
FCLOSE procedure
This procedure writes one or more line terminators to the file identified by
the input file handle. This procedure is separate from PUT because the line
terminator is a platform-specific character or sequence of characters.
Syntax
UTL_FILE.NEW_LINE (
file
IN FILE_TYPE,
lines
IN NATURAL := 3);
System Consultant
73
Example of generating a text file of salary status from the emp table.
create or replace procedure sal_status
(p_filedir in varchar2, p_filename in varchar2)
is
v_filehandle UTL_FILE.FILE_TYPE;
Cursor emp_info is
select ename,sal,deptno
from emp
order by sal desc;
Begin
v_filehandle := UTL_FILE.FOPEN(p_filedir,p_filename,'w');
UTL_FILE.PUTF(v_filehandle,'SALARY REPORT : GENERATED ON
%s\n',SYSDATE);
UTL_FILE.NEW_LINE(v_filehandle);
for v_emp_rec in emp_info
LOOP
UTL_FILE.PUTF(v_filehandle,'DEPARTMENT: %s \n',
v_emp_rec.deptno);
UTL_FILE.PUTF(v_filehandle,' Employee:%s earns: %s\n',
v_emp_rec.ename,v_emp_rec.sal);
END LOOP;
UTL_FILE.PUTF(v_filehandle, '*** END OF REPORT ***');
UTL_FILE.FCLOSE(v_filehandle);
EXCEPTION
WHEN UTL_FILE.INVALID_FILEHANDLE THEN
raise_application_error(-20001,'Invalid File');
WHEN UTL_FILE.WRITE_ERROR THEN
raise_application_error(-20002,'Unable to write file');
End;
System Consultant
74
System Consultant
75
Packages
Database objects that group logically related PL/SQL types, objects and
subprograms
They cannot be called, passed parameters to or nested
There are two parts
Specification
Body
Advantages of Packages
Modularity
allows encapsulation of related types, objects and subprograms in a named
PL/SQL module
easy to understand with simple, clear and well defined interfaces
helps in application development
Easier Application Design
when designing applications, only interface information in package
specifications initially required
can code and compile specification without body
stored subprograms referencing the package can be compiled as well
need not define package bodies until ready to complete the application
Information Hiding
can specify which types, items, and subprograms are public or private
definition of private subprograms is hidden so that only the package (not
the application) is affected if the definition changes
simplifies maintenance and enhancement and protects integrity of the
package
Better performance
when a packaged subprogram is called for the first time, the whole
package is loaded into memory
later calls to related subprograms in the package require no disk I/O
Package Specification
Is an interface to the applications
Declares the types, variables, constants, exceptions, cursors and subprograms
available for use
Holds public declarations, visible to the application
Can be thought of as an operational interface
Scope of the declarations are local to the database schema and global to the
package
Lists the package resources available to applications
Created using CREATE PACKAGE command
System Consultant
76
System Consultant
77
E.g - DBMS_OUTPUT.PUT_LINE
Maintaining a Package
Can drop a package using the DROP command
DROP PACKAGE <packagename>
Example
DROP PACKAGE airlines;
To drop just one construct, remove it from the package and then recompile the
package
System Consultant
78
is
Begin
dbms_output.put_line('Procedure p3');
End z; */
End pk1;
------------------------------Using the Package pk1SQL > Execute PK1.X(4);
2) Use of global variable in a function and procedure Package Specification create or replace package pk2
as
g number;
function m(a number) return number;
procedure n;
end pk2;
Package Body create or replace package body pk2
as
function m(a number) return number
is
Begin
g := a;
return g;
End m;
procedure n
is
Begin
if g >= 100 then
dbms_output.put_line('Discount is 20%');
else
dbms_output.put_line('Discount is 10%');
end if;
end n;
End pk2;
Using the package in a PL/SQL block Declare
System Consultant
79
x number;
Begin
x := pk2.m(700);
pk2.n;
End;
System Consultant
80
System Consultant
81
System Consultant
82
/* Forward declaration of m2 */
System Consultant
83
If the private member is not getting called in any global members then forward declaration
is not required.
create or replace package body prvmembers
is
procedure m1
is
begin
dbms_output.put_line('abc');
end;
/*Creating Private Procedure in the body*/
procedure m2
is
begin
dbms_output.put_line('This is the private member of the package body');
end m2;
end;
/
7) Example of one time only procedure (Procedure in package body)
Useful for setting remote connectivity for front ends.
In the session for the first time any of the members of the package is called then the
procedure will be implicitly invoked.
Then for the future calls of the members of the same package in the same session the
procedure will not get executed.
System Consultant
84
begin
dbms_output.put_line('Welcome to my package');
end pk1;
create or replace package pk1
is
type namelist is table of emp.ename%type index by binary_integer;
v namelist;
cursor cf is select ename from emp;
M cf%rowtype;
procedure first_five;
procedure next_five;
end;
System Consultant
85
System Consultant
86
System Consultant
87
System Consultant
88
System Consultant
89
System Consultant
90
PURITY LEVELS
PRAGMA RESTRICT_REFERENCES
WNDS - Write No Database State
RNDS -
System Consultant
91
Example of WNPS
Package Code
System Consultant
92
return area;
end;
end;
Example of RNPS
Package Specification Code
System Consultant
93
REF CURSORS
Limitations of a normal cursors are -1) A PL/SQL program cannot pass a cursor as a parameter to another program.
2) A PL/SQL program can only open the cursor and process the information within
the program itself.
To overcome these limitations there is a concept of REF CURSOR.
Features of REF CURSOR -1) There can be a TYPE of ref cursor. The variable of this TYPE can be used to
pass the parameters to a program and return value from the cursor.
2) The variable of REF CURSOR type returns the same data type as the cursor
variable.
3) The cursor variable is passed as a parameter to a procedure.
4) The cursor variable takes all the rows from the specified table.
5) These rows are given to the bind variable.
So the parameter passed should satisfy two conditions -a) The parameter should be taken from the TYPE of Ref Cursor.
b) It should be of IN OUT mode.
6) Finally the data retrieved by the cursor variable can be seen through the bind
variable. For this the data type of the bind variable should be REFCURSOR.
7) While executing the procedure bind variable should be directly given. And then by
print statement the data is displayed.
8) The cursor variable's data structure and the procedure block's data structure should
be same.
Advantage of REF CURSOR-Actually we can get the view of the entire data of the table with simplicity using
REF CURSOR.
Without using ref cursor if we have to achieve this then, the parameter passed will
be of variable type
and then the user has to manual loop using cursor to fetch all the records. Here in
REF CURSOR there is no need of looping.
System Consultant
94
System Consultant
95
TYPES
Users can create their own data types by combining previously defined data types
Also called Object types
Object types made up of attributes and members
Creating type Info which holds the attributes
Create or replace type Info as OBJECT
( Name varchar2(30),
Address varchar2(30),
City
varchar2(20),
Phone number(7));
To see the structure of the object Desc Info
Creating Relational Table with User-Defined Type
Using this type in table E.
E table becomes a relational table due to the use of Info user defined datatype.
Create table E
(Empno number,
Emp_Det Info,
Sal number);
See the structure of this relational table E
Desc E
To see the attributes in the Desc command for a relational table
To see the attributes and the datatypes of the user defined datatype
set describe depth 2
Desc E
Inserting data in the table E
Insert into E
Values (1, Info(abc,kothrud,Pune,7876), 7000);
System Consultant
96
System Consultant
97
Altering types
Dropping the type
To drop a type first all the tables in which that type is used should be dropped , then only
the type can be dropped.
User_Types is the in built table for type information.
select type_name,typecode from user_types;
Altering types
The attributes data type size can be increased at any time.
create or replace type h as object
(x number(3),
y number(4));
/*Can increase the size.*/
alter type h
modify attribute x number(10);
/*Cannot decrease the size. */
alter type h
modify attribute x number(9);
Once a attribute is defined in the type then in future its data type cannot be
changed. Only its size can be increased.
Can drop an attribute provided the type is not used in a table.
alter type h
drop attribute x;
Adding an attribute after type creation.
create or replace type t1
as object
(a number);
alter type t1
add attribute b number;
System Consultant
98
VARRAY
Also known as varying arrays
It is an aggregation of values stored in a single column
A single column in the database would point to a group of elements
Can associate a single identifier with an entire collection
Can reference the entire collection as a whole or access the elements individually
To access individual elements, use standard subscripting syntax i.e.
array_name(subscript)
Maximum size must be specified at time of definition
Index has a fixed lower bound of 1 and an extensible upper bound
A varying array allows to store repeating attributes of a record in a single
row.
System Consultant
99
Updating VARRAYs
Individual elements cannot be updated
Entire VARRAY has to be updated if one of the elements has to be changed
To change the value of first index tool of Martin from null to Vernier C
update factory
set tools = tools_va('Vernier C','Sledge', NULL)
where name = 'Martin';
System Consultant
100
System Consultant
101
dbms_output.put_line('--------------------------- ');
end loop;
end;
/
To display the second tool provided for each person
declare
cursor cf is
select * from factory;
vcf cf%rowtype;
x number;
begin
for vcf in cf
loop
x := 0;
dbms_output.put_line('Contact Name -- '|| vcf.name);
for i in 1..vcf.tools.count
loop
if i = 2 then
dbms_output.put_line(vcf.tools(i));
end if;
end loop;
x := x + 1;
end loop;
end;
/
System Consultant
102
end loop;
end loop;
if countOfShaftHolders = 0 then
dbms_output.put_line('Sorry, there are no shaft holders');
end if;
end;
System Consultant
103
System Consultant
104
Nested Table
System Consultant
105
System Consultant
106
System Consultant
107
System Consultant
108
System Consultant
109
Nested Tables
No maximum size
Data is stored out-of-line in a
store table
Do not retain ordering and
subscripts when stored in
database
System Consultant
110
System Consultant
Step 4 Create a table mytable with two fields file_id and file_data
Create table mytable
(file_id number,
file_data clob);
Step 5 A procedure will take file_id and filename from user and transfer data of that file
into the table mytable.
111
System Consultant
CREATE OR REPLACE PROCEDURE insertclob (p_file_id number, filename
VARCHAR2)
AS
v_clob CLOB;
v_bfile BFILE;
BEGIN
INSERT INTO mytable VALUES (p_file_id,empty_clob());
COMMIT;
v_bfile:=BFILENAME('EXTERNAL_FILE11',filename);
select file_data INTO v_clob FROM mytable WHERE file_id=p_file_id FOR
UPDATE;
DBMS_LOB.FILEOPEN(v_bfile);
DBMS_LOB.LOADFROMFILE(v_clob,v_bfile,DBMS_LOB.GETLENGTH(v_bfile));
DBMS_LOB.FILECLOSE(v_bfile);
END;
/
112
System Consultant
(Note In a session, the number of BFILEs that can be opened in one session is limited
by the parameter session_max_open_files and total number of files that can be open is
limited by the parameter max_open_files. These parameters are to be setted in the
init.ora file
session_max_open_files=10
max_open_files=20)
113
System Consultant
where file_id = 1;
DBMS_LOB.READ(v_clob,num,offset,vstore);
dbms_output.put_line(vstore);
end;
/
System Consultant
115
System Consultant
116
System Consultant
TRIGGERS
It is a stored PL/SQL program unit associated with a specific database
table
Oracle executes (fires) the trigger automatically whenever a given
SQL operation affects the table
They are invoked implicitly
They are useful for customizing a database
They should be used only when necessary
Can automatically generate derived column values
Can prevent invalid transactions
Can enforce complex security authorizations
Can enforce referential integrity across nodes in a distributed database
Can enforce complex business rules
Can provide transparent event logging
Can provide sophisticated auditing
Can maintain synchronous table replicates
Can gather statistics on table access
Can derive column values automatically
Can restrict DML operations to regular business hours
117
System Consultant
FOR EACH ROW specifies that the trigger fires once per row
For the trigger to fire, the Boolean expression in the WHEN clause
must evaluate to TRUE
REPLACE can be added to the CREATE statement to drop and recreate the trigger automatically
CREATE TRIGGER flight_update
AFTER INSERT ON reservation
FOR EACH ROW
BEGIN
IF :new.class = F THEN
statements;
ELSIF :new.class = B THEN
statements;
END IF;
END;
Prefix :new is a correlation name that refers to the newly updated
column value
Within a trigger, the :new and :old values of changing rows can be
referenced
A single trigger can handle more than one operation
Use conditional predicates to identify the type of statement used to
invoke the section of code
System Consultant
select ename,sal
from emp
where 1=2;
Whenever a row is inserted in the temp table then that new row
should be transferred in the instemp table
Create or replace trigger trig1
After INSERT on temp
For Each Row
Begin
Insert into InsTemp
Values(:new.ename, :new.sal);
Dbms_output.put_line('Record inserted');
End;
2 ) Table to transfer deleted record
create table deltemp
as
select ename,sal
from emp
where 1=2;
--Whenever a row is deleted from temp table then that row should be
transferred --in Deltemp table
Create or replace trigger Trig2
After DELETE on Temp
For Each Row
Begin
Insert into Deltemp
Values(:old.ename, :old.sal);
End;
3) Table to transfer the old record before updations
create table uptemp
as
select ename,sal
119
System Consultant
from emp
where 1=2;
Whenever a record is updated from the temp table then the old record
shoul go in uptemp table
create or replace trigger trig3
After UPDATE on temp
For Each Row
Begin
Insert into Uptemp
Values(:old.ename, :old.sal);
End;
Referencing old and new values with some other identifier.
create or replace trigger on1
after insert on temp
referencing old as o new as n
for each row
begin
if :n.sal <= 4000 then
raise_application_error(-200012,'sss');
end if;
end;
Use Of Before Clause
1) When a new record is inserted then it should have sal >= 5000
Create or replace trigger trig7
Before INSERT on temp
For Each Row
Begin
If :new.sal < 5000 then
raise_application_error(-20009,'New record sal should be above
5000');
End If;
End;
2) --To prevent user from deleting records of sal >= 3500
120
System Consultant
System Consultant
end;
Use of When Cluase
create or replace trigger useofwhen
after insert on temp
for each row
when (new.job = 'CLERK')
/*After any clerk record is inserted in the temp table, the date and time of
entry will be inserted in the table recofclerk*/
begin
insert into recofclerk
values(sysdate, to_char(sysdate,'hh:mi:ss'));
dbms_output.put_line('All the tables are populated.');
end;
Demo of sequence of execution of row level and statement level triggers
create table trigtab(a number);
create or replace trigger tt1
before insert on trigtab
begin
dbms_output.put_line('Before statement level');
end;
create or replace trigger tt2
before insert on trigtab
for each row
begin
dbms_output.put_line('Before row level');
end;
create or replace trigger tt3
after insert on trigtab
for each row
begin
122
System Consultant
dbms_output.put_line('After row level');
end;
System Consultant
End;
4) Whenever a record is deleted from emp table then the count of records
remaining should be refreshed in the a log table count_emp
create table count_emp (no_of_records number);
create or replace trigger EmpCount
After Delete On Emp
Declare n number;
Begin
select count(*) into n
from emp;
Delete from count_emp;
Insert into count_emp values(n);
dbms_output.put_line('There are now ' || n || ' employees in theemp
table');
end;
124
System Consultant
125
System Consultant
Calling a procedure inside a trigger
CALL TOTSAL
126
System Consultant
127
System Consultant
On Update Cascade
Similar to on delete cascade built in for primary and foreign
key integrity.
create table st
(roll number,
name varchar2(40));
create table res
(roll number,
marks number);
insert into st values(1,'A');
insert into st values(2,'B');
insert into st values(3,'C');
insert into res values(1,90);
insert into res values(2,92);
insert into res values(3,94);
Commit;
create or replace trigger on_update_cascade
after update of roll on st
for each row
Begin
Update res
set res.roll = :new.roll
where res.roll = :old.roll;
End;
128
System Consultant
Instead Of Triggers
Provides a transparent way of modifying views that cannot be
modified directly through INSERT, UPDATE or DELETE statements
because underlying tables contain joins
It is called INSTEAD OF because Oracle fires the trigger instead of
the triggering statement(s)
Users can be transparent to the trigger because they write normal
DML statements against the view and the INSTEAD OF trigger is
used to take care of the modifications
It can be placed on Object Views to insert, update or delete data in the
underlying relational tables
CREATE TRIGGER emp_insert
INSTEAD OF INSERT ON emp_view
BEGIN
statements;
END;
1) Example on Instead of Update on View --Instead of triggers can be used only with views.
--Effective for joins which are based on equi join
-- To have an cascading effect of update on both the tables if columns
are --matching
--Also to update uncommon columns through equi join views
--Step 1 Creating tables s and r;
create table s
(rollno number,
name varchar2(20));
create table r
(rollno number,
marks number);
--Step 2 Inserting records in s and r.
insert into s
values(1,'a');
insert into s
values(2,'b');
129
System Consultant
insert into r
values(1,90);
insert into r
values(2,87);
--Step 3 Creating an Equijoin View on s and r
Create or replace view SR
as
select s.rollno,s.name,r.marks
from s,r
where s.rollno =r.rollno;
--Step 4 Now creating the Instead of Trigger for update on the view SR
Create or replace trigger tig12
Instead Of UPDATE on SR
For Each Row
Begin
/* Updating roll numbers from both the tables s and r */
Update s
set rollno = :new.rollno
where rollno = :old.rollno;
Update r
set rollno = :new.rollno
where rollno = :old.rollno;
/* Updating name column of s table through view.*/
Update s
set name = :new.name
where name = :old.name;
/*Updating marks column of r table through view.*/
Update r
set marks = :new.marks
where marks = :old.marks;
End;
--
130
System Consultant
131
System Consultant
132
System Consultant
133
System Consultant
Assignments
Note All the programs are based on the demonstration tables emp and dept. Before
executing the queries please ensure that the standard records (default) are present.
1)
2)
If the 4th record in the emp table of the job MANAGER then display the entire
record, (each value separated by an hyphen). If the fourth record is not of
MANAGER then display message Manager record not found.
Display the names of the top 3 salary figures from the emp table.
3)
Calculate the compound interest and display it if the principal amount is 50000,
rate of interest is 5 % and duration is 7 years.
4)
Accept job type from the user. Display the message depending upon whether
no rows or one row or several rows are selected.
The message should be any one from the below 3 as per the situation.
JOB TYPE FOUND ONCE
JOB TYPE FOUND MORE THAN ONCE
JOB TYPE NOT FOUND
5)
Display the records of the emp table in the reverse order. It means the last record
should be displayed first and the first record should be displayed at the last.
6)
Check whether the 3rd Clerks salary is greater than the 2nd Clerks salary. If it is
so, then display message as Third has more salary than the second otherwise
display message as Second has more salary than the first
7)
Display the highest salary programmatically without using the max() function
8)
Display the lowest salary programmatically without using the min() function
9)
10)
Accept empno from the user.
If the salary is less than 1500, increase it by 1000.
If the salary is equal to 1500, increase it by 1500.
If the salary is greater than 1500, increase it by 2500.
Ensure that run time errors are properly taken care of.
11) The management has decided to increase salary of employees by 10%. Starting with
lowest paid earner and working up. If at any time salary bill exceeds 35000/- then no
further employees are to be given an increase. Write a PL/SQL block using CURSOR.
134
System Consultant
12) Using while loop technique display all the multiples of 7 between 31 and 48.
13) Create a table Inspection_Details that has one column Readings of numeric type.
Using pl/sql block add numbers, which has the difference of 0.1. The numbers should be
between 0.1 and 6.8.
14) Display the names of the employees who are earning salary less than the average
salary of their own jobs.
15) Display the difference of salary between the oldest and the latest employee.
16) Create a procedure that will take department name as a parameter. The procedure
should delete the record of the employees from the emp table only for the department
name passed.
17) Create a function, which will show 20% of the raised salary for each employee.
18) Create a procedure, which will show the total, highest, lowest and average of the
salary for the job. (Job type is the parameter to be passed.)
19) Create a trigger, which will not allow records to be entered between 1 and 2 pm on
weekdays.
20) Create one trigger which will allow insert, update and delete for a view which is
based on an inner join between tables emp and dept.
21) Create a trigger, which will not allow records getting inserted in table T1 if the
number of records in that table is exceeding 50.
135