R 5
R 5
LABORATORY MANUAL
0:0:4
Name Signature
Prepared by Bindu K
2008
SYLLABUS
DATABASE LAB
R508 0+0+4
TABLE OF CONTENTS
10 PLACEMENT DATABASE 47
11 BANK DATABASE 51
12 FIND HIGHEST PAID SALARY 54
13 SALARY INCREMENT 56
14 UPDATE SALARY USING PROCEDURE 57
15 EXCEPTION HANDLING 59
16 CALCULATE TOTAL SALARY USING 60
FUNCTION
17 FIND COURSE USING FUNCTION 61
18 TABLE MANIPULATION USING CURSOR 63
19 BANK DATABASE USING TRIGGER 67
CYCLE – I
Theoretical Background :
SQL statements are divided into two major categories: data definition language (DDL) and data
manipulation language (DML).
DDL statements are used to build and modify the structure of your tables and other objects in the
database. When you execute a DDL statement, it takes effect immediately.
DML statements are used to work with the data in tables.
Table creation :
SQL> Create Table Faculty (F_code Number Primary Key, F_name Varchar(15));
Table Created
SQL> Create Table Subject (Sub_code Number Primary Key, Sub_name Varchar(15),
Max_mark Number, F_code Number, Foreign Key(F_code) References Faculty(F_code));
Table created.
SQL> Create Table Student (St_code Number Primary Key, St_name Varchar(15), Dob Date,
St_Branch Char(2), Ad_Date Date, Check(St_Branch IN('CS','EC','ME','EE')));
Table created.
SQL> Create Table M_Mark (St_code Number, Sub_code Number, Mark Number(4,2),
Primary Key(St_code,Sub_code), Foreign Key(St_code) References Student(St_code), Foreign
Key(Sub_code) References Subject(Sub_code)) ;
Table created.
Input tables :
SQL> select * from faculty;
F_CODE F_NAME
100 vidya
101 smita
102 bindu
Output :
a) Display the name of faculties.
SQL> select f_name from faculty;
F_NAME
vidya
smita
bindu
e) Display the name of subjects for which atleast one student got below 40%.
SQL> select sub_name from subject,m_mark where mark<(40*max_mark)/100 and
subject.sub_code=m_mark.sub_code group by sub_name having count(distinct(st_code))>=1;
SUB_NAME
dc
oops
h) Display the name of faculties who take more than one subject.
SQL> select f_name from faculty,subject where faculty.f_codeb=bsubject.f_code group by
f_name having count(distinct(sub_code))>1;
F_NAME
bindu
ST_NAME
remya
****************************************************************
Aim:
Create tables Kerala and Tamilnadu and perform the DML operations
Kerala (DistName, LiteracyRate, Population, Area)
TamilNadu (DistName, LiteracyRate, Population, Area)
a) From the above table select common literacy from both the tables.
b) Display the name of all the districts from both the table.
c) Use minus operations on the literacy fields of both tables.
Table creation :
SQL> create table kerala ( distname varchar(15) primary key, L_rate number(5,2),
population number, area number(9,2)) ;
Table created.
SQL> create table tamilnadu( distname varchar(15) primary key, L_rate number(5,2), population
number, area number(9,2));
Table created.
Table insertion:
SQL> insert into kerala values('&distname',&l_rate,&population,&area);
Enter value for distname: ernakulam
Enter value for l_rate: 98
Input tables :
SQL> select * from kerala;
DISTNAME L_RATE POPULATION AREA
ernakulam 98 100000 123456
kasargode 82 110000 234568
calicut 79 120000 235689
trivandrum 92 130000 124578
Output :
1. SQL> select l_rate from kerala intersect select l_rate from tamilnadu;
L_RATE
79
98
2. SQL> select distname from kerala union select distname from tamilnadu;
DISTNAME
calicut
coimbatore
dindigul
ernakulam
kasargode
ooty
pondichery
trivandrum
3. SQL> select l_rate from kerala minus select l_rate from tamilnadu;
L_RATE
82
92
Aim:
Create a table employee with the following fields and create a view which contains the name and
salary > 10000 and update the view by changing employees salary to 10.
Employee( Name, DA, HRA, TA, Salary)
Table creation :
SQL>create table employee(name varchar2(10),da number(10), hra number(10), ta
number(10),salary number(10));
SQL>insert into employee values('&name',&da,&hra,&ta,&salary) ;
Input table :
SQL> select * from employee;
EMP_NAME DA HRA TA SALARY
anil 1000 2000 1000 15000
arun 1000 3000 1500 20000
anu 500 2000 500 9000
beena 900 2500 1000 11000
remya 1500 1000 2000 10000
Output :
SQL> create view emp as select emp_name,salary from employee where salary>10000;
View created.
SQL> select * from emp;
EMP_NAME SALARY
anil 15000
arun 20000
beena 11000
***********************************************************************
MODEL QUESTION
EXP.4 EMPLOYEE DATABASE
3.Write a SQL query that will return information about all managers in the EMPLOYEE table,
ordered alphabetically by name.
4.Write a SQL query that will return information about all employees in Department 40, ordered by
employee number.
5.Write a SQL query that will return information about all employees that are female,
ordered alphabetically by name.
6.To find the minimum salary, maximum salary, and the average salary for each department.
7.Suppose you want to know the minimum commission paid, the maximum commission paid, the
sum of all commissions paid, and the number of employees paid commission. Write one SQL query
to find this information.
8. Suppose you want to find out how many employees are listed in each job category. Write a SQL
query to find this information.
9.Suppose you want to find out how much total salary was paid to each different job category.
That is, how much total were clerks paid, how much were managers paid, etc. Write a SQL query
to find this information.
10.Write a SQL query that will return all the unique department numbers that are represented in the
EMPLOYEE table, ordered by department number.
11.Write a SQL query to return the employee number, name and salary of all females who work in
Department 10.
12.Write a SQL query to return the employee number, name and salary of all male managers,
ordered alphabetically by name.
13.Write a SQL query to return the name and job of all salesmen and managers who are female.
14) Write a query to find the employee number and name for anyone in the EMPLOYEE table
who is a manager and all the clerks working in department 50:
15) write a query to find the employee number and name of anyone who is a manager or a clerk
working in department 50.
16)To return all employees who are not a salesman or a clerk
17)Suppose you want to list all employees who are not in a specific department, say department 10,
but who are clerks.
18)Query to find name of employee whose name contains letters 'u' and 'e'
19)To list all employees who have earned a commission to date:
20)Write a SQL query to find employee number, name and job of all females who are not
managers
21)Write a SQL query to find employee number, name and salary of all employees who make less
than $1000 or more than $4000, ordered by salary.
22)Write a SQL query to find the name and employee number of all salesmen whose name begins
with the letter S.
23)Use the IN operator to write a SQL query to find the name and employee number of all
employees who are analysts or managers, ordered alphabetically by name.
24)Write a SQL query to find the employee number, name, salary and commission of all
employees who have been paid commission and whose salary is greater than 4000.
25)Find the location of the employee named Chen
26)Write an SQL query to find the department number,department name,employee
number,employee name,job,sex and salary and order the rows by employee number within
department number.
27)Find the employee name, employee number and department number for all employees who
work in Houston, with the results in descending employee number order.
28)Retrieve the names and salaries for all employees who earn more than the average salary.
29)Retrieve the names and salaries for all employees who earn more than the average salary.
30)Suppose you need to know the name, job, department name, and location of all female
employees. Write a SQL query that will return this information. Order the list in alphabetical order
by employee name.
31)Suppose you need to know the name, department name, and employee number of all managers.
Write a SQL query that will retrieve this information. Order the list in alphabetical order by
department name.
32)Suppose you need to know the name and department name of the employee who earns the
highest salary. Write a SQL query to return this information.
33)Suppose you need to know the name, department name, and commission of all employees who
were paid commission. Write a SQL query to retrieve this information. Order the list in alphabetical
order by employee name.
34)Suppose you need to know the employee name and department name of all employees that
work in a department that has at least 3 employees. Write a SQL query to retrieve this information.
Order the list in alphabetical order first by department name, then by employee name.
Output:
1. Create Table Department with the following Data
DEPTNO DEPTNAME LOC MGR EXP_BUDG REV_BUDG
10 Accounting Dallas 200 100000 0
30 Research San Francisco 105 125000 0
40 Sales Boston 109 280000 800000
50 Manufacturing Houston 210 130000 0
60 Shipping Houston 215 90000 0
3.Write a SQL query that will return information about all managers in the EMPLOYEE table,
ordered alphabetically by name.
SQL> select * from employee where job = 'mngr' order by name;
4.Write a SQL query that will return information about all employees in Department 40, ordered by
employee number.
SQL> select *from employee where deptno = 40 order by empno;
5.Write a SQL query that will return information about all employees that are female,
ordered alphabetically by name.
SQL>select * from employee where sex = 'f' order by name;
6.To find the minimum salary, maximum salary, and the average salary for each department.
SQL>select deptno, min(salary), max(salary), avg(salary) from employee group by deptno;
7.Suppose you want to know the minimum commission paid, the maximum commission paid, the
sum of all commissions paid, and the number of employees paid commission. Write one SQL query
to find this information.
SQL >select min(comm), max(comm), sum(comm), count(comm) from employee;
8. Suppose you want to find out how many employees are listed in each job category. Write a SQL
query to find this information.
SQL> select job, count(*) from employee group by job;
9.Suppose you want to find out how much total salary was paid to each different job category.
That is, how much total were clerks paid, how much were managers paid, etc. Write a SQL query
to find this information.
SQL>select job, sum(salary) from employee group by job;
10.Write a SQL query that will return all the unique department numbers that are represented in the
EMPLOYEE table, ordered by department number.
SQL>select distinct deptno from employee order by deptno;
11Write a SQL query to return the employee number, name and salary of all females who work in
Department 10.
SQL>select empno, name, salary from employee where sex = 'f' and deptno = 10;
12.Write a SQL query to return the employee number, name and salary of all male managers,
ordered alphabetically by name.
SQL>select empno, name, salary from employee where sex = 'm' and job = 'mngr' order by name;
13.Write a SQL query to return the name and job of all salesmen and managers who are female.
SQL>select name, job from employee where sex = 'f' and (job = 'slsm' or job = 'mngr');
14) Write a query to findthe employee number and name for anyone in the EMPLOYEE table
who is a manager and all the clerks working in department 50:
SQL> select empno, name, job, deptno from employee
where job = 'mngr' or (job = 'clrk' and deptno = 50);
15) write a query to find the employee number and name of anyone who is a manager or a clerk
working in department 50.
SQL> select empno, name from employeewhere (job = 'mngr' or job = 'clrk') and deptno = 50;
16)To return all employees who are not a salesman or a clerk
SQL>select name, empno from employee where job not in ('slsm','clrk');
(or)
SQL>select name, empno from employee where job != 'slsm' and job <> 'clrk';
17.Suppose you want to list all employees who are not in a specific department, say department 10,
but who are clerks.
SQL> select name, job, deptn o from employee where job = 'clrk'
and deptno ^= 10;
18 Query to find name of employee whose name contains letters 'u' and 'e'
SQL>select empno, name from employee where name like '%u%e%';
SQL>select empno, name, salary from employee where salary not between 1000 and 4000 order
by salary;
22)Write a SQL query to find the name and employee number of all salesmen whose name begins
with the letter S.
SQL>select name, empno from employee where name like 's%' and job = 'slsm';
23)Use the IN operator to write a SQL query to find the name and employee number of all
employees who are analysts or managers, ordered alphabetically by name.
SQL>select name, empno from employee where job in ('anlt', 'mngr') order by name;
24) Write a SQL query to find the employee number, name, salary and commision of all
employees who have been paid commission and whose salary is greater than $4000.
SQL>select empno, name, salary, comm from employee where comm is not null and comm > 0
and salary > 4000;
25) to find the location of the employee named Chen
SQL>select name, loc from employee, deptwhere name = 'chen' and employee.deptno =
dept.deptno;
26) write an sql query to find the department number,department name,employee
number,employee name,job,sex and salary and order the rows by employee number within
department number.
SQL> select employee.deptno, deptname, empno, name, job, sex, salary from employee, dept
where employee.deptno = dept.deptno deptno order by employee.deptno, empno;
27)to find the employee name, employee number and department number for all employees who
work in Houston, with the results in descending employee number order.
SQL>select name, empno, deptno from employee where deptno in(select deptno from dept where
loc = 'houston') order by empno desc;
28)to retrieve the names and salaries for all employees who earn more than the average salary.
SQL>select name, salary from employee where salary >(select avg(salary) from employee);
29)to retrieve the names and salaries for all employees who earn more than the average salary.
SQL>select name, salary from employee where salary >(select avg(salary) from employee);
30)Suppose you need to know the name, job, department name, and location of all female
employees. Write a SQL query that will return this information. Order the list in alphabetical order
by employee name.
SQL>select name, job, deptname, loc from employee, deptwhere sex = 'F'and employee.deptno =
dept.deptnoorder by name;
32)Suppose you need to know the name and department name of the employee who earns the
highest salary. Write a SQL query to return this information.
SQL> select name, deptname from employee, dept where employee.deptno = dept.deptno
and salary = (select max(salary) from employee);
NAME DEPTNAME
Watson Research
33)Suppose you need to know the name, department name, and commission of all employees who
were paid commission. Write a SQL query to retrieve this information. Order the list in alphabetical
order by employee name.
SQL>select name, comm, deptname from employee, is331.dept where employee.deptno =
dept.deptno and comm is not null and comm > 0 order by name;
NAME COMM DEPTNAME
Allen 8000 Sales
Schwartz 5300 Sales
Smith 1300 Sales
34)Suppose you need to know the employee name and department name of all employees that
work in a department that has at least 3 employees. Write a SQL query to retrieve this information.
Order the list in alphabetical order first by department name, then by employee name.
SQL>select name, deptname from employee, dept where employee.deptno = .deptno
and employee.deptno in (select deptno from employee group by deptno having count(*) >2)
order by deptname, name;
NAME DEPTNAME
Allen Sales
Schwartz Sales
Smith Sales
Di Salvo Shipping
McDonnel Shipping
Simpson Shipping
*****************************************************************
CYCLE-II
PL/ SQL PROGRAMS
With PL/SQL, you can use SQL statements to manipulate ORACLE data and
flow-of-control statements to process the data. Moreover, you can declare
constants and variables, define subprograms (procedures and functions),
and trap runtime errors. Thus, PL/SQL combines the data manipulating power
of SQL with the data processing power of procedural languages.
A block (or sub-block) lets you group logically related declarations and
statements. That way you can place declarations close to where they are used.
The declarations are local to the block and cease to exist when the block
completes.
[DECLARE
-- declarations]
BEGIN
-- statements
[EXCEPTION
-- handlers]
END;
Aim :Write a PL/SQL program to insert square numbers into table-Square and non square
numbers into NonSquare table upto a limit. Also write PL/SQL code to print
odd square numbers from the square table.
Algorithm :
1 Start
2 Create tables square and nonsquare
3 declare the cursor c
4 enter the limit
5 loop for I varies from 1 to n
6 set flag as zero
7 loop for j varies from 1 to I
8 if I = j*j then set flag as 1
9 end if
10 end loop
11 if flag =1 then insert the value into square table
12 else insert into nonsquare table.
13 End if
14 end loop
15 open cursor c
16 fetch c into variable and exit when c%not found
17 print the odd numbers
18 end loop
19 close cursor
20 end
Table creation :
SQL > create table square (num int);
Table created.
SQL > create table nonsquare (no int);
Table created.
Program:
declare
n number;
temp number;
cursor odd is
select * from square where mod(i,2)!=0;
flag number:=0;
begin
n:=&limit;
for i in 1..n
loop
flag:=0;
for j in 1..n
loop
if(i=j*j) then
insert into square values(i);
flag:=1;
end if;
end loop;
if(flag<>1) then
insert into nonsquare values(i);
end if;
end loop;
open odd;
dbms_output.put_line('odd squares are');
loop
fetch odd into temp;
exit when(odd%notfound);
dbms_output.put_line(temp);
end loop;
close odd;
end;
Output
Enter value for limit : 17
odd squares are
1
9
9
16
SQL> select * from nonsquares;
2
3
5
6
7
8
10
11
12
13
14
15
17
******************************************************************
Aim : Write a PL/SQL program to accept the customer number and print the bill for the
same. The charges are calculated as follows:
Units consumed Charge
<20 Nil
20-100 50% per unit
101-300 75% per unit
301-500 150% per unit
>500 225% per unit
Input table
SQL> select * from customer;
CUST ID PRE-READ PAST -READ
Program
declare
cid number;
p1 number;
p2 number;
u number;
chrge varchar(5);
begin
cid := &customerno;
select pre_read,past_read into p1,p2 from customer where custid=cid;
u:=p1-p2;
if u<20 then
chrge:='NIL';
elsif u> 20 and u<100 then
chrge:=u*50/100;
elsif u>101 and u<300 then
chrge:= u*75/100;
elsif u>301 and u<500 then
chrge:= u*150/100;
else
chrge:=u* 225/100;
endif;
dbms_output.put_line('ELECTRICITY BILL');
dbms_output.put_line('customer No:'||cid);
dbms_output.put_line('Present Reading:'||p1);
dbms_output.put_line('Past Reading:'||p2);
dbms_output.put_line('Units Consumed:'||u);
dbms_output.put_line('Charge:'||chrge);
end;
\
Output:
Enter the value for customerno: 103
ELECTRICITY BILL
Customer No:103
Present Reading:780
Past Reading:200
Units consumed:580
charge:1305
Program :
declare
m number;
l number;
r number := 0;
d number
begin
m := & number;
l := m;
while m > 0
loop
d:=(mod(m,10);
r := r + (d*d*d);
m:=trunc(m/10);
dbms_output.put_line (m);
end loop;
if (l=r) then
dbms_output.put_line(l||' is an armstrong number');
else
dbms_output.put_line(l||' is not an armstrong number');
end if;
end;
output :
case 1 :
*****************************************************
Aim : Write a PL/SQL program to input two numbers. If the first number is greater than
second then swap it, else if first number is less than second raise it to its power else double it.
Algorithm :
1 start
2 declare the variables
3 enter two numbers a and b
4 if a>b then t = a , a = b , b = t
5 else if a<b then , a= a**a
6 else a= 2*a
7 end if
8 Print a and b
9 stop
Program:
Declare
a number(5);
b number(5);
t number(5);
begin
a := &a;
b := &b;
dbms_output.put_line( 'initial value of a = '||a ||' b = '||b )
if a>b
then
t := a;
a:= b;
b:=t;
elsif A<B then
a:=a**a;
b:=b**b;
ELSE
a:=2*a;
b:=2*b;
end if;
dbms_output.put_line('final value of a = '||a ||' b = '||b);
end;
Output :
case 1 :
Aim :
Write a PL/SQL program to reverse a string and check whether it is a palindrome
or not.
Algorithm :
1 start
2 declare the variables
3 enter the string
4 find the length of the string
5 loop for I =1 to length, reverse the string
6 end loop
7 if the reversed string = string entered then
8 print the string is a palindrome
9 else
10 print the string is not a palindrome
11 stop
Program :
declare
g varchar2(20);
r varchar2(20);
begin
g:='&g';
dbms_output.put_line('the given text :'||g);
for i in reverse 1.. length(g) loop
r:= r || substr(g,i,1);
end loop;
dbms_output.put_line('the reversed text :'||r);
if r=g then
dbms_output.put_line('the given text is palindrome ');
else
dbms_output.put_line('the given text is not palindrome ');
end if;
end;
Output :
case 1 :
enter value for g: malayalam
CYCLE – III
Theoretical Background:Cursors :
A cursor is a mechanism by which you can assign a name to a "select statement" and
SELECT course_number
from courses_tbl
where course_name = name_in;
The command that would be used to fetch the data from this cursor is:
FETCH c1 into cnumber;
This would fetch the first course_number into the variable called cnumber;
The final step of working with cursors is to close the cursor once you have finished using it.
The basic syntax to CLOSE the cursor is:
CLOSE cursor_name;
For example, you could close a cursor called c1 with the following command:
CLOSE c1;
Example:
A function that demonstrates how to use the cursor:
CREATE OR REPLACE Function FindCourse
( name_in IN varchar2 )
RETURN number
IS
cnumber number;
CURSOR c1
IS
SELECT course_number
from courses_tbl
where course_name = name_in;
Begin
open c1;
fetch c1 into cnumber;
if c1%notfound then
cnumber := 9999;
end if;
close c1;
RETURN cnumber;
END;
While dealing with cursors, you may need to determine the status of your cursor. The
following is a list of the cursor attributes that you can use.
%ISOPEN
-- Returns TRUE if the cursor is open, FALSE if the cursor is closed.
%FOUND
- Returns INVALID_CURSOR if cursor is declared, but not open; or if cursor has been closed.
− Returns NULL if cursor is open, but fetch has not been executed.
− Returns TRUE if a successful fetch has been executed.
− Returns FALSE if no row was returned
%NOTFOUND
- Returns INVALID_CURSOR if cursor is declared, but not
open; or if cursor has been closed.
- Return NULL if cursor is open, but fetch has not been executed.
- Returns FALSE if a successful fetch has been executed.
- Returns TRUE if no row was returned.
%ROWCOUNT
- Returns INVALID_CURSOR if cursor is declared, but not
open; or if cursor has been closed.
- Returns the number of rows fetched.
The ROWCOUNT attribute doesn't give the real row count until you have iterated through
the entire cursor. In other words, you shouldn't rely on this attribute to tell you how
many rows are in a cursor after it is opened.
exception_section]
END [function_name];
When you create a procedure or function, you may define parameters. There are three types
of parameters that can be declared:
1 IN - The parameter can be referenced by the procedure or function. The value of the
parameter can not be overwritten by the procedure or function.
2 OUT - The parameter can not be referenced by the procedure or function, but the value of
the parameter can be overwritten by the procedure or function.
3 IN OUT - The parameter can be referenced by the procedure or function and the value of
the parameter can be overwritten by the procedure or function.
BEGIN
open c1;
fetch c1 into cnumber;
if c1%notfound then
cnumber := 9999;
end if;
close c1;
RETURN cnumber;
EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR-
'||SQLERRM);
END;
This function is called FindCourse. It has one parameter called name_in and it returns a
number. The function will return the course number if it finds a match based on course
name. Otherwise, it returns a 99999.
PL/SQL Procedure
The syntax for a procedure is:
CREATE [OR REPLACE] PROCEDURE procedure_name [ (parameter [,parameter]) ] IS
[declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [procedure_name];
When you create a procedure or function, you may define parameters. There are three types
of parameters that can be declared:
1 IN - The parameter can be referenced by the procedure or function. The value of the
parameter can not be overwritten by the procedure or function.
2 OUT - The parameter can not be referenced by the procedure or function, but the value of
the parameter can be overwritten by the procedure or function.
3 IN OUT - The parameter can be referenced by the procedure or function and the value of
the parameter can be overwritten by the procedure or function.
A simple example of a procedure:
CREATE OR REPLACE Procedure UpdateCourse
( name_in IN varchar2 )
IS
cnumber number;
cursor c1 is
select course_number
from courses_tbl
where course_name = name_in;
BEGIN
open c1;
fetch c1 into cnumber;
if c1%notfound then
cnumber := 9999;
end if;
insert into student_courses
( course_name,
course_number)
values ( name_in,
cnumber );
commit;
close c1;
EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR-
'||SQLERRM);
END;
This procedure is called UpdateCourse. It has one parameter called name_in. The
procedure will lookup the course_number based on course name. If it does not find a
match, it defaults the course number to 99999. It then inserts a new record into the
student_courses table.
Program:
declare
pcode number:=10;
cursor c is
select apcode,jcode from applicant,jobs
where jobs.qual=applicant.qual and vacancy>0 and off_sal>=exp_sal
and (jplace=place or place is null);
begin
for i in c
loop
insert into placedlist
values(pcode,i.apcode,i.jcode);
pcode:=pcode+1;
end loop;
end;
update applicant
set pon='y'
where apcode in(select apcode from placedlist);
declare
cursor c is
select count(jcode) c_jcode,jcode from placedlist
group by jcode;
begin
for i in c
loop
update jobs
set vacancy=vacancy-i.c_jcode
where jcode=i.jcode;
end loop;
end;
Input:
SQL > Select * from jobs;
Output :
SQL > Select * from plcdlist;
Aim :
A bank has an acco_master table where it holds the current status of a clients bank
Program:
SQL>set serveroutput on
SQL>declare
Output:
SQL>select * from acco_trans;
AccNo Trans_Date Deb_Cre Amt Pro
1012 12-Jan-08 debit 5000 yes
1024 14-Feb-08 credit 100 yes
1987 04-Dec-07 credit 1000 yes
2345 17-Mar-08 credit 20000 yes
Aim : Write a PL/SQL program using cursors to select the five highest paid employees from the
emp table.
Input Table :
SQL> SELECT ename, empno, sal FROM emp ORDER BY sal DESC;
ENAME EMPNO SAL
KING 7839 5000
SCOTT 7788 3000
FORD 7902 3000
JONES 7566 2975
BLAKE 7698 2850
CLARK 7782 2450
ALLEN 7499 1600
TURNER 7844 1500
MILLER 7934 1300
WARD 7521 1250
MARTIN 7654 1250
ADAMS 7876 1100
JAMES 7900 950
SMITH 7369 800
Program :
DECLARE
CURSOR c1 is
SELECT ename, empno, sal FROM emp
ORDER BY sal DESC; -- start with highest paid employee
my_ename VARCHAR2(10);
my_empno NUMBER(4);
my_sal NUMBER(7,2);
BEGIN
OPEN c1;
FOR i IN 1..5 LOOP
FETCH c1 INTO my_ename, my_empno, my_sal;
EXIT WHEN c1%NOTFOUND; /* in case the number requested */
/* is more than the total */
/* number of employees */
Aim :
Write a Procedure to increase the salary for all the employees in the EMP table :
Input table :
SQL> select * from emp;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 17-DEC-80 700 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
Program :
create or replace procedure inc(i number) is
begin
update emp set sal =sal+i;
end;
/
Procedure created.
Aim :
write a procedure to increase the salary for the specified employee using empno in the emp
table based on the following criteria: increase the salary by 5% for clerks, 7% for salesman ,
10% for analyst, 20 % for manager and 25% for president. activate using pl/sql block.
Input table :
SQL> select * from emp;
EMPNO ENAME JOB MGR HIREDATE SAL COMM
DEPT
7369 smith clerk 7902 17-dec-80 800
20
Procedure :
create or replace procedure designation(eno number) is
begin
update emp set sal=sal+sal*5/100 where job ='clerk' and empno=eno;
update emp set sal=sal+sal*7/100 where job='salesman' and empno=eno;
update emp set sal=sal+sal*10/100 where job='analyst' and empno=eno;
update emp set sal=sal+sal*20/100 where job='manager' and empno=eno;
update emp set sal=sal+sal*25/100 where job='president' and empno=eno;
end;
/
Procedure created.
Program :
SQL> declare
begin
designation(7369);
end;
/
PL/SQL procedure successfully completed.
Output:
SQL> select * from emp;
EMPNO ENAME JOB MGR HIREDATE SAL COMM
DEPT
7369 SMITH CLERK 7902 17-DEC-80 840 20
Procedure:
Create or replace procedure raise_salary(emp_id integer, increase real) is
current_salary real;
salary_missing exception;
BEGIN
select sal into current_salary from emp where empno=emp_id;
if current_salary is null then
raise salary_missing;
else
update emp set sal = sal+increase where empno = emp_id;
end if;
Exception
WHEN NO_DATA_FOUND THEN
insert into emp_audit values (emp_id, 'No such number');
WHEN salary_missing THEN
insert into emp_audit values (emp_id,'salary is null');
END raise_salary;
Aim : Create a function that queries the employee table and returns the total salary for a specified
department.
Program:
CREATE FUNCTION dept_salary (dnum NUMBER)
RETURN NUMBER IS
total_wages number(11,2) : =0;
SELECT sum(sal, nvl(comm,0)) into total_wages FROM emp
WHERE deptno = dnum;
dbms_output.put_line('Total Wages=' ||TO_CHAR (total_wages));
return total_wages;
end dept_salary;
Input table :
Assume the emp table contains the following records:
Output:
Total Wages = 3250
Aim :
Create a function called FindCourse. It has one parameter called name_in and it returns a
number. The function will return the course number if it finds a match based on course name.
Otherwise, it returns a 99999.
Program:
CREATE OR REPLACE Function FindCourse ( name_in IN varchar2 )
RETURN number IS
cnumber number;
cursor c1 is
select course_number from courses_tbl where course_name = name_in;
BEGIN
open c1;
fetch c1 into cnumber;
if c1%notfound then
cnumber := 9999;
end if;
close c1;
RETURN cnumber;
EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20001,'An error was encountered - '||SQLCODE||'
-ERROR- '||SQLERRM);
END;
Function Created.
You could then reference your new function in an SQL statement as follows:
SQL >select course_name, FindCourse(course_name) as course_id from courses
where subject = 'Mathematics';
Input:
SQL > Select * from course;
CourseNo CourseName
10 mba
20 btech
30 medicine
40 mca
50 Bsc
Output:
Course_Name :B Tech
Course_No :20
PL/SQL procedure successfully completed
Result: PL/SQL program has been executed.
Aim :
A relation T1(e,f) whose tuples are pairs of integers. Using cursors the program
will delete every tuple whose first component is less than the second, and insert the reverse
tuple into T1.
Program:
DECLARE
/* Output variables to hold the result of the query: */
a T1.e%TYPE;
b T1.f%TYPE;
/* Cursor declaration: */
CURSOR T1Cursor IS
SELECT e, f
FROM T1
WHERE e < f
FOR UPDATE;
BEGIN
OPEN T1Cursor;
LOOP
/* Retrieve each row of the result of the above query into PL/SQL variables: */
FETCH T1 Cursor INTO a, b;
/* If there are no more rows to fetch, exit the loop: */
EXIT WHEN T1 Cursor %NOTFOUND;
/* Delete the current tuple: */
DELETE FROM T1 WHERE CURRENT OF T1Cursor;
/* Insert the reverse tuple: */
INSERT INTO T1 VALUES(b, a);
END LOOP;
/* Free cursor used by the query. */
CLOSE T1Cursor;
END;
CYCLE IV
DATABASE TRIGGER
Database Triggers
Theoretical Background:
A database triggers is stored PL/SQL program unit associated with a specific database table or view.
The code in the trigger defines the action the database needs to perform whenever some database
manipulation (INSERT, UPDATE, DELETE) takes place.
Unlike the stored procedure and functions, which have to be called explicitly, the database triggers
are fires (executed) or called implicitly whenever the table is affected by any of the above said DML
operations.
A database trigger has three parts :
1.A triggering event
2.A trigger constraint (Optional)
3.Trigger action
A triggering event can be an insert, update, or delete statement or a instance shutdown or startup
etc. The trigger fires automatically when any of these events occur A trigger constraint specifies a
Boolean expression that must be true for the trigger to fire. This condition is specified using the
WHEN clause. The trigger action is a procedure that contains the code to be executed when the
trigger fires.
Types of Triggers
The following are the different types of triggers.
Row triggers and statement triggers
A Row trigger fires once for each row affected. It uses FOR EACH ROW clause. They are useful if
trigger action depends on number of rows affected.
Statement Trigger fires once, irrespective of number of rows affected in the table. Statement
triggers are useful when triggers action does not depend on
While defining the trigger we can specify whether to perform the trigger action (i.e. execute trigger
body) before or after the triggering statement. BEFORE and AFTER triggers fired by DML
statements can only be defined on tables.
BEFORE triggers The trigger action here is run before the trigger statement.
AFTER triggers The trigger action here is run after the trigger statement.
INSTEAD of Triggers provide a way of modifying views that can not be modified directly using
DML statements.
LOGON triggers fires after successful logon by the user and LOGOFF trigger fires at the start of
user logoff.
Points to ponder
A trigger cannot include COMMIT, SAVEPOINT and ROLLBACK.
We can use only one trigger of a particular type .
A table can have any number of triggers.
We use correlation names :new and :old can be used to refer to data in command line and data in
table respectively.
Theoretical Background:
An AFTER UPDATE Trigger means that Oracle will fire this trigger after the UPDATE operation
is executed.
The syntax for an AFTER UPDATE Trigger is:
CREATE or REPLACE TRIGGER trigger_name
AFTER UPDATE
ON table_name
[ FOR EACH ROW ]
DECLARE
-- variable declarations
BEGIN
-- trigger code
EXCEPTION
WHEN ...
-- exception handling
END;
Restrictions:
Table Creation :
SQL > create table depositor (accno primary key , cname char(10));
SQL > create table borrower (loanno number , cname char(10));
SQL > create table loan( loanno number , brname char(10),amt number);
SQL > create table acct-t( acctno number , bal number, brname char(10), foreign key (acctno)
references depositor (acctno);
Table insertion:
SQL > insert into depositor values (&accno , &cname );
Enter value for accno : 101
Enter the value for cname : Alan
SQL > insert into acct-t values( &acctno , &bal , '&brname ');
Enter value for accno : 101
Enter the value for bal : 20000
Enter the value for brname : tvm
Input table :
SQL > select * from depositor;
ACCNO CNAME
101 Alan
102 Ann
103 Ben
SQL > select * from acct-t;
ACCNO BAL BRNAME
101 20000 tvm
102 10500 ekm
103 5000 tcr
Trigger:
SQL > create or replace trigger account after update of bal on acct-t for each row
declare
c varchar2 (20)
begin
if (:new.bal < :old.bal) then
insert into loan values (:new.accno, :new.brname , :old.bal-:new.bal);
select cname into c from depositor where accno = new.accno;
insert into borrower values (:new.accno,c);
endif;
end;
/
Trigger created.
Query :
SQL > update acct-t set bal = bal-5000 where acctno=101;
1 row updated.
Output:
SQL >select * from borrower;
LOANNO CNAME
101 Alan
References
1. Database System Concepts - Henry F Korth, Abraham Silbershatz, Mc Graw Hill 2nd
edition.
2. An Introduction to Database Systems - C.J.Date (7th Edition) Pearson Education
Asia
3. Database Principles, Programming and Performance – Patrick O’Neil, Elizabeth O’Neil
4. An Introduction to Database Systems - Bibin C. Desai