Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
ORACLE 9i
PL/SQL
By System Consultant
System Consultant
Table of Contents
3
Programming Basics with PL/SQL
Structure of PL/SQL
Standard PL/SQL code segment is called a Block
A block consists of three parts or sections
Declaration Part
Executable Part
Exception Handling Part
Declaration Part
optional part where variables are defined
Executable Part
mandatory part which consists of executable statements
Exception Handling Part
System Consultant
4
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
5
declare
z number;
a varchar2(10);
begin
z := &z;
a := '&a';
dbms_output.put_line('Z is '|| z);
dbms_output.put_line('A is '|| a);
end;
-------------------------------------------------------------------------------
A constant number has to declared and initialized in the declare block only
using
CONSTANT keyword. Value cannot be changed
declare
r CONSTANT number :=100;
begin
/* r := r + 100; Not possible*/
dbms_output.put_line(r);
end;
/*Assigning value to variable from a column of a table using select into clause*/
declare
x number;
begin
% Type Attribute
Provides datatype of a variable or column
Useful when declaring a variable that refers to a column in a database
exact datatype of column need not be known
if column definition changes, variable datatype changes accordingly at
runtime
Example
oldfare fare.first_fare%TYPE;
newfare oldfare%TYPE;
declare
a emp.ename%type;
b emp.sal%type;
c emp.deptno%type;
/*Using %TYPE attribute for variable data type*/
begin
select ename,sal,deptno
into a,b,c
from emp
where ename = 'KING';
dbms_output.put_line(a ||'-'|| b ||'-' || c);
end;
%RowType Attribute
Useful when declaring a record variable having same structure as a row in a
table or view, or as a row fetched from a cursor
Fields in the record have same names and datatypes as the columns in the
table/view
Example
emp_rec employee%ROWTYPE;
A specific field can be referenced using
emp_rec.emp_num;
System Consultant
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
dbms_output.put_line('Passed');
else
dbms_output.put_line('Failed');
end if;
end;
System Consultant
8
-----------------------------------------------------
IF-THEN-ELSIF Structure
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
create table adm
(Name varchar2(30),
Marks number(3),
College varchar2(30),
Fees number(5));
System Consultant
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;
end;
System Consultant
10
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;
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;
11
Labels
If the variables names of the outer and inner blocks are same then labels have to be
used within the inner block to avoid ambiguity.
<<outer_block>>
declare
x number;
begin
<<inner_block>>
declare
x number := 100;
begin
dbms_output.put_line('Value of the inner block x is ' || x);
-- Giving value of x of the inner block to the outer block x
outer_block.x :=inner_block. x;
end;
x := x + 500;
dbms_output.put_line('Value of the outer block x is ' || x);
end;
/
LOOPS
The ability to repeat or skip sections of a block can be achieved with the usage of
LOOP or GOTO statements
There are three forms of the LOOP statement
LOOP
WHILE-LOOP
FOR-LOOP
LOOP Statement
LOOP repeats a sequence of statements
Statements to be repeated are placed between keyword LOOP and END LOOP
With each iteration of the loop, the sequence of statements is executed, then
control resumes at the top of the loop
LOOP
statements;
END LOOP;
EXIT Statement
Used to complete a loop if further processing in a loop is undesirable or
impossible
There are two forms of the EXIT statement
EXIT
EXIT-WHEN
System Consultant
12
Forces a loop to complete unconditionally
Must be placed inside a loop
LOOP
statements;
IF <condition> THEN
EXIT; -- exit loop immediately
END IF;
END LOOP;
-- control resumes here
Example of Loop
/*To show 1 to 10 on screen*/
Declare
x number;
Begin
x := 1;
Loop
dbms_output.put_line(x);
x := x + 2;
exit when x > 10;
End Loop;
dbms_output.put_line(end);
End;
Declare
x number;
Begin
x := 5;
Loop
Insert into five
values(x);
x := x + 5;
exit when x > 50;
End Loop;
End;
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 )
System Consultant
13
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
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.
14
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
declare
x number;
Begin
x := 1;
System Consultant
15
while x <=15
Loop
dbms_output.put_line(x);
x := x + 1;
End Loop;
end;
The loop will never get executed since the condition is wrong from the start of the
iteration.
Basic Loop
Declare
x number;
Begin
x := 1;
System Consultant
16
Loop
dbms_output.put_line(x);
exit when x = 1;
x := x + 1;
End Loop;
dbms_output.put_line('End of program');
End;
/
Nested Loops
Expected Output
1 1 12%
1 2 11%
1 3 10%
2 4 9%
2 5 8%
2 6 7%
3 7 6%
3 8 5%
3 9 4%
4 10 3%
4 11 2%
4 12 1%
12 rows selected.
declare
q number;
m number;
d number;
dis varchar2(10);
c number;
System Consultant
17
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
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
System Consultant
18
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));
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);
end;
declare
System Consultant
19
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
Declare
TYPE empdetails IS RECORD
(eno Emp.Empno%type,
name Emp.Ename%type,
s Emp.Sal%type);
VE empdetails;
Begin
20
Declare
TYPE si IS RECORD
(p number,
n number,
r number := 4.5);
/* r variable of si type has been given value. */
VSI si;
x number;
Begin
VSI.p := 5000;
VSI.n := 6;
x := (VSI.p * VSI.n * VSI.r) / 100;
dbms_output.put_line(x);
End;
Declare
V personal_details;
Begin
V.name := 'John';
V.Addr.sector := 'S1';
V.Addr.colony := 'Model';
V.Addr.bldg_name := 'Hill View';
V.Addr.pincode := 6775;
dbms_output.put_line('The building name is ' || V.Addr.bldg_name);
dbms_output.put_line('The pincode is ' ||V.Addr.pincode);
End;
-------------------------------------
System Consultant
21
%Rowtype with Record
declare
type t1 is record
(ed emp%rowtype,
dd dept%rowtype);
VT1 t1;
Begin
dbms_output.put_line(VT1.ed.ename);
dbms_output.put_line(VT1.dd.dname);
end;
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;
22
CLOSE
Cursor must be declared before it can be referenced using the OPEN, CLOSE or
FETCH statements
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
evaluates to FALSE if last FETCH failed because no more rows were
available
System Consultant
23
%ROWCOUNT
returns the number of rows FETCHed from the active set so far
%ISOPEN
evaluates to TRUE if an explicit cursor is open
evaluates to FALSE if an explicit cursor is closed
Examples of Cursor
1)
To transfer names and sal of employees from emp table where sal >= 2500 in table
try1
create table try1
(no number,
ename varchar2(50),
sal number);
Declare
Cursor cf is
select ename,sal
from emp
where sal >= 2500;
M cf%rowtype;
N number;
Begin
Open cf;
N := 0;
Loop
Fetch cf into M;
Exit when cf%notfound;
N := cf%rowcount;
Close cf;
End;
Accepting the job from user and finally showing how many such jobs are there.
Declare
Cursor cf is
select *
from emp
where job ='&J';
System Consultant
24
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;
----------------------------------------------------------------------
25
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
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;
Declare
Cursor cf is
select *
from emp;
M cf%rowtype;
Begin
Open cf;
Loop
fetch cf into M;
if cf%rowcount = 3 then
dbms_output.put_line(M.empno||'-'||M.ename||'-'||M.sal||'-'||M.deptno);
System Consultant
26
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;
27
Begin
For mrec in cf
Loop
dbms_output.put_line(mrec.ename||' '||mrec.sal||' '||mrec.deptno);
End Loop;
End;
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;
open cf('CLERK');
LOOP
FETCH CF INTO M;
EXIT WHEN CF%NOTFOUND;
System Consultant
28
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
29
Declare
Cursor cf is
select * from esal
For Update of sal;
M cf%rowtype;
Begin
Open cf;
Loop
Fetch cf into M;
System Consultant
30
exit when cf%notfound;
Else
M.Sal := 5000;
End If;
Update esal
set sal = M.Sal
Where Current Of cf;
End Loop;
End;
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
31
Although OPEN, CLOSE and FETCH statements cannot be used to manipulate
the SQL% cursor, the attributes can be used to access its context area
Attributes evaluate to NULL, before the cursor is opened automatically
The following four cursor attributes can be used to access the SQL%
cursors context area
SQL%NOTFOUND
SQL%FOUND
SQL%ROWCOUNT
SQL%ISOPEN
SQL%NOTFOUND
evaluates to TRUE if an INSERT, UPDATE or DELETE statement
affected no rows, else it evaluates to FALSE
SQL%FOUND
logical opposite of SQL%NOTFOUND
evaluates to TRUE if an INSERT, UPDATE or DELETE affected one or
more rows, else it evaluates to FALSE
SQL%ROWCOUNT
returns the number of rows affected by an INSERT, UPDATE or DELETE
statement
SQL%ISOPEN
Oracle automatically closes an implicit cursor after executing its
associated SQL statement
For an implicit cursor SQL%ISOPEN always evaluates to FALSE
If SQL%Found Then
dbms_output.put_line('Record found and it is deleted');
End If;
If SQL%NotFound Then
dbms_output.put_line('No record is present of the given name.');
End If;
End;
32
Declare
C number; := 0;
Begin
Update Emp
set sal = sal + 500
where deptno = &deptno;
/*If no record is updated since the deptno supplied is wrong then giving
the customised error message.*/
If SQL%Rowcount = 0 then
dbms_output.put_line('No records are updated since the department number entered
is not in the table.');
End if;
PL/SQL Tables
33
Range of binary_integer is -2147483647 to + 2147483647
7) Size is unconstrained (Table size grows as the rows are added to the table).
8) Can visualize a Pl/SQL table as a single dimensional vertical array, which can
hold unlimited elements.
9) Suitable for storing and displaying the values of one column of a table given
by a cursor.
Each name from the emp table is given to the vname plsql table by using cursor.
Then those names from vname table are displayed .
Declare
Type nametable IS TABLE OF CHAR(10) INDEX BY BINARY_INTEGER;
/*Creating variable vname of nametable type.*/
vname nametable;
Cursor cf is select ename from emp;
i number;
vrows number;
/*i is for the loop and vrows is for displaying the total names from the vname
table*/
Begin
Open cf;
i := 1;
Loop
Fetch cf into vname(i); /*Transferring each ename into vname
table*/
Exit when cf%NotFound;
vrows := cf%rowcount;
i := i + 1;
End Loop;
System Consultant
34
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;
declare
Type discount is TABLE OF number
INDEX By Binary_Integer;
d discount;
Begin
d(5) := 90;
d(2) := 50;
d(8) := 70;
d(11) := 67;
d(14) := 68;
d(1) := 1;
d(23) := 5;
d(23) := 51;
dbms_output.put_line('The value at 23 index number is ' || d(23));
dbms_output.put_line('The value at index number 6 is ' || d(6));
--dbms_output.put_line('The value at index number 2 is ' || d(2));
if d.EXISTS(6) Then
dbms_output.put_line(d(6));
else
dbms_output.put_line('There is no element in the sixth row');
end if;
35
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
36
EXCEPTIONS
Introduction to Exceptions
37
Examples of Exception handling
1) NO_DATA_FOUND error (Variable is not having any value.)
declare
n emp.ename%type;
s emp.sal%type;
begin
select sal into s
from emp
where ename = '&n';
dbms_output.put_line('Salary is '|| s);
/* Exception
When NO_DATA_FOUND then
dbms_output.put_line('No record'); */
end;
declare
s emp.sal%type;
begin
select sal into s
from emp;
dbms_output.put_line('The salary is '|| s );
Exception
When TOO_MANY_ROWS then
dbms_output.put_line('Variable can hold only one value at a time');
dbms_output.put_line('Please specify the name of person for getting the
salary');
end;
Exception
System Consultant
38
When ZERO_DIVIDE then
dbms_output.put_line('Cannot divide by zero!!!');
end;
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);
Exception
System Consultant
39
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
declare
referential_integrity EXCEPTION;
PRAGMA EXCEPTION_INIT( referential_integrity, -2292);
begin
Delete from dept1
where deptno = &deptno;
commit;
exception
when referential_integrity then
dbms_output.put_line('The record cannot be deleted, because related record found in
emp1 table');
end;
40
declare
s emp.sal%type;
v_error_code number;
v_error_message varchar2(255);
begin
select sal into s from emp;
exception
when others then
v_error_code := SQLCODE;
v_error_message := SQLERRM;
Insert into error_log values(v_error_code, v_error_message);
commit;
end;
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 */
41
User-defined Exceptions
42
Begin
p := &p;
if p < 100 then
raise EX;
else
si := (p * n * r) / 100;
dbms_output.put_line('The Simple Interest is '|| si);
end if;
Exception
When EX then
dbms_output.put_line('The principle amt should be greater than or equal to
100.');
end;
--------------------------------------------------------------------------------------
RAISE_application_error
This can be used to create user defined error message, which can be more
descriptive than named exceptions.
Syntax - :
Raise_application_error(error number,error message);
where error number is any parameter between -20,000 and -20,999.Error message
is text that is associated with this error. The message parameter must be less than 512
characters.
Example of Raise_application_error
declare
maths number;
Begin
maths := &maths;
43
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
44
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
45
END [<procedurename>];
46
Examples of Procedures
47
-- While executing
--exec pr3 (1,'o',800) -----> (No deptno parameter given!!!)
Named notations
48
1. Positional Method -- exec dept_rec(20,'Purchase','Mumbai');
2. Named Method
a. exec dept_rec(p_loc => 'Bangalore',p_deptno => 30);
b. exec dept_rec(p_deptno =>20, p_dname => 'Inspection', p_loc =>
'Pune');
c. exec dept_rec(p_dname =>'Stores', p_loc => 'Mumbai', p_deptno =>
10);
3. Combination Method
After positional there can be named parameters, but after named there cannot
be positional parameters.
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
49
Using local variable for out parameter when procedure is called inside another
block.
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
x := (x * x);
End;
50
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);
dbms_output.put_line(a);
End;
System Consultant
51
7) IN OUT example from with respect to database
a)
create or replace procedure salrise(salary IN OUT number) is
Begin
salary := salary + (salary * 0.20);
End;
/*Salrise procedure will increment the sal by 20% and give the value to the calling plsql
block.*/
b)
Declare
n emp.ename%type;
s emp.sal%type;
Begin
n := '&n';
select sal into s
from emp
where ename = n;
dbms_output.put_line('The old salary is ' || s);
/*Now calling the procdure Salrise and giving s as a IN parameter*/
Salrise(s);
/*After giving the salary as a parameter the salary value gets incremented by 20% */
dbms_output.put_line('The changed salary is '|| s);
/*updating the table*/
Update emp
set sal = s
where ename = n;
dbms_output.put_line('Salary of ' || n || ' is updated in the table.');
Exception
When NO_DATA_FOUND then
dbms_output.put_line('No such name');
end;
--------------------------------------------------------------------------------------------------
System Consultant
52
Declaring Sub procedures
Begin
log_emp;
End;
System Consultant
53
Handled or Unhandled Exceptions for a procedure getting called in another.
exception
when others then
dbms_output.put_line('A Run Time Error has occurred.');
end;
If the innerproc procedure is not having any error handler then the error handler
outer procedure gets executed.
AUTHID CURRENT_USER
If a procedure reads data from table and performs some DML then AUTHID
CURRENT_USER is applicable. Due to this clause the owner of the procedure only can
execute this procedure and read or perform DML. Even if the owner has given execute
privilege of such a procedure to any other user, still the other user cannot execute the
procedure. So from data security point of view this clause is helpful.
The following scenario will explain this concept.
54
grant resource, create session to a2;
----------------------------------------------------------
Without AUTHID CURRENTUSER
conn a1/a1
create table t1(a number);
insert into t1 values(1);
commit;
-----------------------------------------------------------
create or replace procedure t1_data
is
x number;
begin
select a into x from t1;
dbms_output.put_line(x);
end;
----------------------------------------------
grant execute on t1_data to a2;
-------------------------------------------------
conn a2/a2
exec a1.t1_data --- Data is shown.
conn a1/a1
-------------------------------------------
conn a2/a2
exec a1.t1_data1 -- Data is not shown. Throws error.
System Consultant
55
System Consultant
56
Functions
Syntax
Format
Calling a Function
57
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;
58
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';
Else
disp := 'Failed';
End If;
RETURN disp;
End;
59
marks number,
result char(30));
RETURN vloc;
End;
b)
-- First declare two bind variables location and deptname
System Consultant
60
--SQL> variable deptname varchar2(100) (size is imp)
--SQL> variable location varchar2(100)
Begin
:location := getdetails(30, :deptname);
End;
61
DBMS_SQL
DBMS_DDL
DBMS_JOB
UTL_FILE
System Consultant
62
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
63
You should use dynamic SQL in cases where static SQL does not support the operation
you want to perform, or in cases where you do not know the exact SQL statements that
must be executed by a PL/SQL procedure. These SQL statements may depend on user
input, or they may depend on processing work done by the program. The following
sections describe typical situations where you should use dynamic SQL and typical
problems that can be solved by using dynamic SQL
In PL/SQL, you can only execute the following types of statements using dynamic SQL,
rather than static SQL:
Data definition language (DDL) statements, such as CREATE, DROP, GRANT, and
REVOKE
Session control language (SCL) statements, such as ALTER SESSION and SET ROLE
You can use dynamic SQL to create applications that execute dynamic queries, whose full
text is not known until runtime. Many types of applications need to use dynamic queries,
including:
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
64
DBMS_SQL is used to write dynamic SQL in stored procedure and to parse DDL
statements.
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.
language_flag Determines how Oracle handles the SQL statement. The following
options are recognized:
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.
65
end;
System Consultant
66
DBMS_DDL Package
67
exec compile_procedure('PX1');
68
DBMS_JOB Package
Enables the scheduling and execution of PL/SQL programs.
Example
Every next day a new record should get added in the table djt1.
begin
dbms_job.submit
(
job => :jobno,
what => 'P1;',
next_date => trunc(sysdate),
interval => 'trunc(sysdate + 1)'
);
commit;
end;
System Consultant
69
Change the system date to the next date. The t1 table gets the next
value of the sequence.
Again repeat the process.
Exec dbms_job.Remove(1)
70
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.
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
%s Substitute this sequence with the string value of the next argument in the argument list.
71
FCLOSE procedure
This procedure closes an open file identified by a file handle.
NEW_LINE procedure (Can specify how many blank lines are required.
Default is 1)
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
72
Example of generating a text file of salary status from the emp table.
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
73
74
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
75
Package Body
Packaged objects and subprograms must be referenced using the dot notation
packagename.typename
packagename.objectname
packagename.subprogramname
E.g - DBMS_OUTPUT.PUT_LINE
System Consultant
76
Maintaining a Package
Examples of Packages -
1) Creating a package of 3 procedures -
Package Specification
Package Body -
create or replace package body pk1
is
procedure x(a number)
is
Begin
dbms_output.put_line('Procedure p1');
End x;
procedure y(b number)
is
Begin
dbms_output.put_line('Procedure p2');
End y;
/*Suppose in the package body if all the procedures are not written then it will
give error.*/
/*procedure z(c number)
is
Begin
System Consultant
77
dbms_output.put_line('Procedure p3');
End z; */
End pk1;
-------------------------------
Using the Package pk1-
SQL > Execute PK1.X(4);
Package Specification -
Package Body -
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;
Declare
x number;
Begin
System Consultant
78
x := pk2.m(700);
pk2.n;
End;
System Consultant
79
3) Use of Type in a Procedure -
Package Specification -
Package Body -
Package Specification -
80
Package Body -
begin
bodyless.x := bodyless.x + 100;
dbms_output.put_line('Now the value of the x variable of bodyless package is ' ||
bodyless.x);
end;
/* Note-- Execute the block 3-4 times, you will see that the values of x and y are
getting changed.
But disconnect or close the session and start the session again.
The original values of the x and y from the package gets initialized.
*/
System Consultant
81
procedure m1
is
begin
m2;
end;
end;
Example of forward declaration of a private member
procedure m2
is
begin
dbms_output.put_line('This is the private member of the package body');
end m2;
end;
System Consultant
82
If the private member is not getting called in any global members then forward declaration
is not required.
83
create or replace package body pk1
is
procedure p1
is
begin
dbms_output.put_line('p1');
end p1;
procedure p2
is
begin
dbms_output.put_line('p2');
end p2;
begin
dbms_output.put_line('Welcome to my package');
end pk1;
end;
System Consultant
84
create or replace package body pk1
is
i Number;
procedure first_five
is
begin
for i in 1..5
loop
dbms_output.put_line(v(i));
end loop;
end first_five;
procedure next_five
is
begin
for i in 6..10
loop
dbms_output.put_line(v(i));
end loop;
end next_five;
begin
i := 0;
open cf;
loop
i := i + 1;
fetch cf into M;
v(i) := M.ename;
exit when cf%notfound;
end loop;
end
85
create or replace package pk1
is
average_sal number;
function calc_sal_deviation(s number) return number;
procedure sal_status(s number);
end;
exec pk1.SAL_STATUS(800);
exec pk1.SAL_STATUS(4000);
86
8) Example of Overloaded Members
begin
if z > 0 then
dbms_output.put_line('The number is positive');
else
dbms_output.put_line('The number is negative');
end if;
end p;
procedure p
is
begin
dbms_output.put_line('No parameter is passed');
end p;
end pk1;
System Consultant
87
Example of overloaded members
Parameter data types can be same, but names should be different.
88
Example of Persistent Cursors
89
PURITY LEVELS
PRAGMA RESTRICT_REFERENCES
end;
System Consultant
90
Package Body Code -
Example of WNPS
Package Code
91
return area;
end;
end;
Example of RNPS
-----------------------------
System Consultant
92
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.
93
Example of REF CURSOR
Package Specification
End PRC;
Package Body
End DeptDetails;
End PRC;
94
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
Create table E
(Empno number,
Emp_Det Info,
Sal number);
Desc E
To see the attributes and the datatypes of the user defined datatype
set describe depth 2
Desc E
Insert into E
Values (1, Info(abc,kothrud,Pune,7876), 7000);
System Consultant
95
Note Primary key, Unique, Foreign Key and check constraint cannot be given to
the column of user defined data type.
Constraint can be given to the attributes of the column for that specific table.
For the name attribute of det column giving constraint
Syntax -- ColumnName.AttributeName
create table j1
(roll number,
det info,
constraint ccc unique(det.name));
Select * from E X
where X.Emp_Det.Name = abc;
System Consultant
96
Altering types
Altering types
Once a attribute is defined in the type then in future its data type cannot be
changed. Only its size can be increased.
alter type h
drop attribute x;
alter type t1
add attribute b number;
System Consultant
97
VARRAY
Example In a factory table there are workers using different tools. Each worker is
using say 3 numbers of tools. Thus if a single worker is taking 3 tools then that workers
name will come thrice in the table. So there will be data redundancy. Varrays will repeat
values that change for a particular column which will save the storage space.
Step 2 - Create a table having one of the column as the varray column
based on the varray type.
98
Step 3 Inserting record in the factory table
V is an alias table created for the tool names. TABLE function is used to simplify the
process of selecting data from varying arrays.
Conditional records
Summary records
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
99
Creating customized and advance report using PL/SQL blocks
100
end loop;
end;
/
101
end loop;
if countOfShaftHolders = 0 then
dbms_output.put_line('Sorry, there are no shaft holders');
end if;
end;
System Consultant
102
Creating a varray from a type
Multiple attributes for a single record and multiple sets of attributes for a single record.
103
Nested Table
Table within a table
A table is represented as a column within another table
There is no limit to the number of rows in the nested table for each
row in the main table.
Basically used for mapping master-detail relationships between tables.
i.e. In the parent table there would be one column, which will store the location of
the nested table.
Example --
There is main table Fare_Tab1.
It has columns such as Route_Coe,Route_Desc,Origin,Destination, Firts_Fare,
Bus_Fare,Eco_Fare and journey_hrs.
There is a type as table Fs_Nst_Type.
This type table holds column such as Flightno, Airbusno,Deprt_Time,
Flight_Day1 and Flight_Day2.
Now we are trying to establish the relation between Fare_Tab1 table and this
type table Fs_Nst_Type.
104
Step 1 -- Create a type Flight_Sch_type to hold details for a single flight.
Step 2 -- Create a type of table which will hold the multiple rows of the
nested table.
Step3 -- Create the main table which will have the nested table through a
column of the main table
SYNTAX
INSERT INTO <master_table_name>
VALUES(<master_table_column1_value>,
<master_table_columnN_value,
nested_table_type(nested_column(attribute1_value>,...<attributeN_value>),
nested_column(attribute1_value>,
<attributeN_value>)));
System Consultant
105
Here in this insert statement for one route_code 'Goa-Ban' 2 nested rows of F2
and F3 are inserted.
SYNTAX in Oracle 8i
SELECT <master_table_columns>,
<nested_alias>.<attributes_from_type>
FROM THE (SELECT <nested_column>
FROM <master_table>
WHERE <master_table_condition>) <nested_alias>, <master_table>
WHERE <nested_table_condition>;
To display the nested row for the route code 'Goa-Ban' for flighno F1
In Oracle 9i Table function is used instead of THE clause which makes the
query very easy to understand
So Syntax in 9i is
Select master_table_cols, Alias.Neste_Table_Cols
From Master_Table, Table(Master_Table.Nested_Table) Alias
To see all attribute columns of the Nested Table we can use * with alias name of
the nested table
select route_code, NT.*
from Fare_Tab1, Table(Fare_Tab1.Flight_Sch_Det) NT
where route_code = 'Goa-Ban' And NT.flightno = 'F3'
System Consultant
106
SYNTAX
UPDATE THE (SELECT <nested_column>
FROM <master_table>
WHERE <master_table_condition>) <nested_alias>
SET <nested_alias>.<attribute1_name> = <value>,...,
WHERE <nested_table_condition>;
Update THE
(Select Flight_Sch_Det
from Fare_Tab1 F
where F.route_code = 'Goa-Ban')
NT
Set
NT.Flight_day1 = 5
where NT.Flightno = 'F3';
Syntax in 9i
107
Deleting a row from the nested table
SYNTAX in 9i
DELETE FROM THE
(SELECT <nested_column>
FROM <master_table>
WHERE <master_table_condition>) <nested_alias>
WHERE <nested_table_condition>;
Deleting a row in 9i
To delete a nested row of Flight_day2 having value 5 for a route_code
Goa-Ban
108
LOB BLOB and CLOB are the tow types of LOBs. B is binary and C is character data.
LOB files are stored inside the database. Since the files are inside db, they can be
manipulated thorough oracle. A max of 4GB data can be stored in a BLOB or CLOB data
type.
Directory is a non-schema object owned by SYS user. It is used for managing the
operating system files (that are external to oracle). Directory object will help to write data
into external file or read data from an external file.
BfileName function It initializes a Bfile column to point to an external file. Use the
BfileName function as part of an Insert statement to initialize a Bfile column by
associating it with a physical file in the server file system. A Bfile can be initialized to
NULL and updated later by using the BFILENAME function.
Step 1- There is file mytextfile.txt in C:\MyData path. The mytextfile.txt has some
sample text.
Step 2 A user should have create any directory and read directory privileges. These
privileges are taken from SYS user.
109
System Consultant
Step 4 Create a table mytable with two fields file_id and file_data
Step 5 A procedure will take file_id and filename from user and transfer data of that file
into the table mytable.
110
System Consultant
DBMS_LOB.LOADFROMFILE(v_clob,v_bfile,DBMS_LOB.GETLENGTH(v_bfile));
DBMS_LOB.FILECLOSE(v_bfile);
END;
/
exec insertclob(1,'mytextfile.txt');
111
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)
Where
loc is locator of the LOB
num is number of bytes/characters to be read
offset is offset in bytes/characters from the start of the LOB
buff is output buffer for the read operation
declare
v_clob clob;
num number;
offset number;
vstore varchar2(20);
begin
num := 7;
offset :=1;
select file_data into v_clob
from mytable
112
System Consultant
where file_id = 1;
DBMS_LOB.READ(v_clob,num,offset,vstore);
dbms_output.put_line(vstore);
end;
/
Where
loc is locator of the LOB
declare
loc clob;
len number;
Begin
select file_data into loc from mytable
where file_id = 1;
len := DBMS_LOB.GETLENGTH(loc);
dbms_output.put_line(len);
end;
/
Where
loc is locator of the LOB
num is number of bytes/characters to write
offset is offset in bytes/characters from the start of the LOB for
write operation
113
System Consultant
Declare
loc clob;
num number;
offset number;
vstore varchar2(80);
lenlob number;
vlen number;
Begin
-- In the Select statement For Update clause is must, so that the row gets locked.
select file_data into loc from mytable where file_id=1 for update;
-- To get the total number of characters in a lob.
-- Use getlength function of DBMS_LOB
lenlob := DBMS_LOB.getLength(loc);
-- vstore is having the additional text
vstore := 'This is new line';
-- Now the length of the new text to be added should also be known since that value is
one
vlen := Length(vstore); -- Length of the new text in vstore variable
offset := lenlob + 1; -- Due to +1 in offset the text starts from --one space next
DBMS_LOB.Write(loc,vlen,offset,vstore);
end;
/
exec insertclob(2,'mytextfile.txt');
114
System Consultant
DBMS_LOB.Erase
Declare
loc clob;
num number;
offset number;
Begin
num := 5;
offset := 1;
DBMS_LOB.Erase(loc,num,offset);
End;
/
115
System Consultant
116
System Consultant
TRIGGERS
Syntax --
CREATE [OR REPLACE] TRIGGER <triggername>
BEFORE|AFTER
INSERT|DELETE|UPDATE OF <columnnames> ON <tablename>
[FOR EACH ROW]
WHEN (<condition>)
<PL/SQL Block>
Name in the ON clause identifies the database table associated with the
trigger
The trigger event specifies the SQL DML statement (INSERT, DELETE or
UPDATE) that affects the table
AFTER specifies that the trigger fires after the manipulation is done
BEFORE specifies that the trigger fires before the manipulation is
done
By default, a trigger fires once per table
FOR EACH ROW specifies that the trigger fires once per row
117
System Consultant
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 re-
create 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;
1)
-- Main table
create table temp
as
select * from emp;
118
System Consultant
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
119
System Consultant
where 1=2;
Whenever a record is updated from the temp table then the old record
shoul go in uptemp table
120
System Consultant
3) If a salary is updated then it should be always greater than the old salary.
4) Whenever a new record is inserted then the cost value should be always
greater than all the existing cost values in the table.
121
System Consultant
/*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;
122
System Consultant
end;
123
System Consultant
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
124
System Consultant
125
System Consultant
Procedure Code
126
System Consultant
127
System Consultant
On Update Cascade
create table st
(roll number,
name varchar2(40));
Commit;
128
System Consultant
Instead Of Triggers
insert into r
129
System Consultant
values(1,90);
insert into r
values(2,87);
--Step 4 Now creating the Instead of Trigger for update on the view SR
130
System Consultant
Insert into r
values(:new.rollno, :new.marks);
End;
Delete from s
where rollno = :old.rollno;
Delete from r
where rollno = :old.rollno;
End;
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) 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.
2) 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
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