0% found this document useful (0 votes)
17 views21 pages

RDBMS Practical Assignment Solutions1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views21 pages

RDBMS Practical Assignment Solutions1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Assignment 1 - Stored Procedure

Practical Assignment SET A


1. Using Bank Database
a. Write a procedure to transfer amount of 1000 Rs. from acc_no 10 to acc_no 20.
b. Write a procedure withdrawal for the following:
i) Accept balance amount and acc_no for withdrawal as input parameters.
ii) Check if input amount is less than actual balance of accounts.
iii) If input amount is less, give the message “Withdrawal allowed from account”. Otherwise give the message “Withdrawal
not allowed from account”. Update the balance .

SET B
1. Using Bus Transportation Database
a. Write a procedure to list the drivers working on a particular date shift wise.Accept the date as an input parameter.
b. List the bus_no and drivers allocated to the buses which are running from ‘Nasik Road’ to ‘CBS’ on date .

SET C
1. Using Student Competition Database
a. Write a procedure to count the number of competitions which come under the type ‘Sports’ and no. of competitions which
come under the type ‘academics’.
b. Write a stored procedure which accepts year as input and gives a list of all competitions held in that year.

Assignment 2 - Stored Functions


SET A
Using Bank Database
a) Write a function that returns the total number of customers of a particular branch. ( Accept branch name as input
parameter.)
b) Write a function to find the maximum loan amount approved.

create table branch(bid int primary key,bname varchar(15),bcity varchar(15));

create table customer(cno int primary key,cname varchar(15),caddr varchar(15),city varchar(15));

create table loan_app(lno int primary key,l_amt_required money,l_amt_approved money,l_date date);

create table b_c_loan(bid int references branch(bid),cno int references customer(cno),lno int
references loan_app(lno));

Insert Values :-
insert into branch values(1,'aundh','nashik');
insert into branch values(2,'deccon','pune');
insert into branch values(3,'m.g.road','mumbai');
insert into branch values(4,'rk','nashik');
insert into branch values(5,'cbs','nashik');

insert into customer values(1,'anil','as colnay','pune');


insert into customer values(2,'sunil','as colnay','pune');
insert into customer values(3,'ajay','as colnay','pune');
insert into customer values(4,'samadhan','mg colnay','nashik');
insert into customer values(5,'mahesh','mg colnay','nashik');

insert into loan_app values(1,'50000','40000','02-07-2014');


insert into loan_app values(2,'60000','60000','15-07-2014');
insert into loan_app values(3,'23000','22000','29-07-2014');
insert into loan_app values(4,'45000','45000','23-07-2014');
insert into loan_app values(5,'35000','34000','23-08-2014');

insert into b_c_loan values(1,1,1);


insert into b_c_loan values(1,2,5);
insert into b_c_loan values(1,2,4);
insert into b_c_loan values(1,4,2);
insert into b_c_loan values(1,3,4);
insert into b_c_loan values(1,4,4);
insert into b_c_loan values(1,5,2);
insert into b_c_loan values(1,5,2);

a) Write a function that returns the total number of customers of a particular branch.( Accept
branch name as input parameter.)

create function s4a_a(varchar ) returns integer as $$


declare
name alias for $1;
cnt integer :=0;
temp record;
begin
for temp in select customer.cno,bname from customer,branch,b_c_loan where
customer.cno=b_c_loan.cno and
branch.bid=b_c_loan.bid loop
if temp.bname=name then
cnt:=cnt+1;
end if;
end loop;
return cnt;
end;
$$ language plpgsql;

b) Write a function to find the maximum loan amount approved


create function s4a_b() returns money as $$
declare
m money :='0';
temp record;
begin
for temp in select l_amt_approved from loan_app loop
if m<temp.l_amt_approved then
m:=temp.l_amt_approved;
end if;
end loop;
return m;
end;
$$ language plpgsql;
SET B:
Using Project-Employee database
a) Write a function to accept project name as input and returns the number of employees working on the project.
b) Write a function to find the number of employees whose date of joining is before ‘03/10/2010’

create table project(pno int primary key,pname varchar(15),ptype varchar(15),duration int);


CREATE TABLE

create table emp(eno int primary key,ename varchar(15),j_date date);


CREATE TABLE

create table prog_emp(pno int references project(pno),eno int references emp(eno),s_date date);
CREATE TABLE

Input Values:-

insert into project values(1,'system','computer',100);


insert into project values(2,'robotics','computer',100);
insert into project values(3,'cloud network','computer',50);
insert into project values(4,'microprocessor','electronics',150);
insert into project values(5,'eye senser','electronics',250);
insert into project values(6,'remote car','meachinical',75);

insert into emp values(1,'anil','04-04-2010');


insert into emp values(2,'ajay','23-05-2010');
insert into emp values(3,'nadim','18-08-2011');
insert into emp values(4,'samadhan','28-12-2012');
insert into emp values(5,'mahesh','28-12-2012');

insert into prog_emp values(1,1,'04-04-2010');


insert into prog_emp values(1,2,'23-05-2010');
insert into prog_emp values(2,2,'23-05-2010');
insert into prog_emp values(3,1,'25-05-2011');
insert into prog_emp values(3,1,'25-05-2011');
insert into prog_emp values(3,4,'28-12-2012');
insert into prog_emp values(4,5,'28-12-2013');

Write a function to accept project name as input and returns the number of employees working
on the project.

create or replace function ass2SetD_3(varchar ) returns integer as $$


declare
name alias for $1;
cnt integer :=0;
temp record;
begin
for temp in select emp.eno,pname from emp,prog_emp,project where emp.eno=prog_emp.eno and
prog_emp.pno=project.pno loop
if temp.pname=name then
cnt:=cnt+1;
end if;
end loop;
return cnt;
end;
$$ language plpgsql;

Write a function which accepts employee name and prints the details of the project which the
employee works on.

create or replace function ass2SetD_2(enm varchar) returns integer as $$


declare
temp record;
begin
for temp in select project.pno, pname,ptype,duration ,ename from project, emp, prog_emp where
project.pno=prog_emp.pno and emp.eno =prog_emp.eno loop
if temp.ename=enm then
Raise Notice ' Project No : %',temp.pno;
Raise Notice ' Project Name : %',temp.pname;
Raise Notice ' Project type : %',temp.ptype;
Raise Notice ' Project Duration : %',temp.duration;
end if;
end loop;
return 1;
end;
$$ language plpgsql;
Assignment 3 : Cursors

Using the Warehouse database

a) Write a stored function using cursors to accept a city from the user and to list all warehouses in the city.
create function fun2(nm varchar(20))returns void as '
declare c1 cursor for select wname from warehouse where city=nm;
wn char(30);
Begin
open c1;
loop
fetch c1 into wn;
exit when not found;
raise notice''warehouse name:-%'',wn;
end loop;
close c1;
end '
language 'plpgsql';
CREATE FUNCTION

b) Write a stored function using cursors to find the list of items whose cost is between Rs.5000 to 10000
create function fun4()returns void as '
declare c3 cursor for select ino,description from items where cost between 500
and 1000;
ino int;
d text;
begin
open c3;
loop
fetch c3 into ino,d;
exit when not found;
raise notice''item nos:%'',ino;
raise notice''description:%'',d;
end loop;
close c3;
end '
language 'plpgsql';
CREATE FUNCTION

SET B
Company –Person database
Company(Name varchar(30),address (50),city varchar(20), phone varchar(10), share _value money)
Person(pname varchar(30),pcity varchar (20))
Company_Person are related with M to M relationship with descriptive attribute No_of_shares. Integer

company4=# create table company(name varchar(20) primary key,add


varchar(50),phone varchar(20),share_value money);NOTICE: CREATE TABLE / PRIMARY
KEY will create implicit index "company_pkey" for table "company"
CREATE TABLE
company4=# create table person(pname varchar(30) primary key,pcity
varchar(20));NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index
"person_pkey" for table "person"
CREATE TABLE
company4=# create table cp(name varchar(30) references company(name) on delete
cascade,pname varchar(30) references person(pname) on delete
cascade,nos_of_share int);
CREATE TABLE
company4=# \d
List of relations
Schema | Name | Type | Owner
--------+---------+-------+----------
public | company | table | postgres
public | cp | table | postgres
public | person | table | postgres
(3 rows)

company4=# insert into company values('infosys','abc','020-665544','$5000000');


INSERT 0 1
company4=# insert into company values('infosystem','abc','020-
665545','$6000000');
INSERT 0 1
company4=# insert into company values('info','pune','020-665545','$7000000');
INSERT 0 1
company4=# insert into company values('infotec','pune','020-665543','$5500000');
INSERT 0 1
company4=# insert into company values('wipro','pune','020-665345','$6500000');
INSERT 0 1
company4=# insert into person values('Rahul','pune');
INSERT 0 1
company4=# insert into person values('Vidhyadhar','pune');
INSERT 0 1
company4=# insert into person values('sachin','mumbai');
INSERT 0 1
company4=# insert into person values('darshan','mumbai');
INSERT 0 1
company4=# insert into person values('shiva','mumbai');
INSERT 0 1
company4=# insert into cp values('infosys','Rahul',10);
INSERT 0 1
company4=# insert into cp values('infosystem','Vidhyadhar',25);
INSERT 0 1
company4=# insert into cp values('infotec','darshan',5);
INSERT 0 1
company4=# insert into cp values('info','sachin',15);
INSERT 0 1
company4=# insert into cp values('wipro','shiva',12);
INSERT 0 1
company4=# select * from company;
name | add | phone | share_value
------------+------+------------+---------------
infosys | abc | 020-665544 | $5,000,000.00
infosystem | abc | 020-665545 | $6,000,000.00
info | pune | 020-665545 | $7,000,000.00
infotec | pune | 020-665543 | $5,500,000.00
wipro | pune | 020-665345 | $6,500,000.00
(5 rows)

company4=# select * from person;


pname | pcity
------------+--------
Rahul | pune
Vidhyadhar | pune
sachin | mumbai
darshan | mumbai
shiva | mumbai
(5 rows)

company4=# select * from cp;


name | pname | nos_of_share
------------+------------+--------------
infosys | Rahul | 10
infosystem | Vidhyadhar | 25
infotec | darshan | 5
info | sachin | 15
wipro | shiva | 12
(5 rows)

a) Write a stored function using cursors to transfer the shares owned by ‘Sachin ‘ to ‘Rahul’.
create function b11()returns void as '
declare cb1 cursor for select pname,nos_of_share from cp where pname=''sachin'';
p varchar(30);
n int;
begin
open cb1;
loop
fetch cb1 into p,n;
exit when not found;
update cp set nos_of_share=nos_of_share+n where pname=''Rahul'';
update cp set nos_of_share=nos_of_share-n where pname=p;
end loop;
close cb1;
end '
language 'plpgsql';
CREATE FUNCTION

b) Write a stored function using cursors to print the total number of distinct investors along with its total invested value.

create function f11()returns void as '


declare c10 cursor for select count(cp.name),sum(share_value) from
person,company,cp where person.pname=cp.pname and company.name=cp.name;
cnt int;
sm money;
begin
open c10;
loop
fetch c10 into cnt,sm;
exit when not found;
raise notice''Count : %'',cnt;
raise notice''Sm : %'',sm;
end loop;
close c10;
end '
language 'plpgsql';

SET C
Student –Marks database
Student (rollno integer,name varchar(30),address varchar(50),class varchar(10)) Subject(Scode varchar(10),subject
name varchar(20))
student and subject are related with M-M relationship with attributes marks scored. Create a RDB in 3NF for the above
and solve the following.

select * from student;


rno | name | addrs | class
-----+-----+---------------+------
101 | ABC | Sadhashiv Peth | Fy
102 | DEF | Sadhashiv Peth | Fy
103 | GHI | Sadhashiv Peth | Fy
104 | JKL | Nana Peth | Sy
105 | MNO | Nana Peth | Sy
(5 rows)

marks4=# select * from subject;


scode | sname
-------+-------------
1 | Science
2 | Comp.Science
3 | Electronics
(3 rows)

marks4=# select * from ss;


rno | scode | marks
-----+------+------
101 | 1 | 80
102 | 1 | 85
103 | 1 | 81
104 | 2 | 76
105 | 3 | 71
104 | 1 | 69
105 | 1 | 79
101 | 2 | 79
101 | 3 | 89
102 | 2 | 71
102 | 3 | 72
103 | 2 | 76
103 | 3 | 64
104 | 3 | 69
105 | 2 | 89
(15 rows)

a) Write a stored function using cursors, to accept a address from the user and display the name,subject and the marks of
the students staying at that address.

create function c1(addrs varchar(20))returns void as '


declare c11 cursor for select name,subject,marks from student,subject,ss where
student.rno=ss.rno and subject.scode=ss.scode and addrs=''Sadhashiv Peth'';
n varchar(20);
s varchar(20);
m int;
begin
open c11;
loop
fetch c11 into n,s,m;
exit when not found;
raise notice''Name:%'',n;
raise notice''Subject Name:%'',s;
raise notice''Marks:%'',m;
end loop;
close c11;
end '
language 'plpgsql';
CREATE FUNCTION

b) Write a stored function using cursors which will calculate total and percentage of each student
create function c22()returns void as '
declare c21 cursor for select rno,count(scode),sum(marks) from ss group by rno;
r int;
s int;
m int;
p float;
begin
open c21;
loop
fetch c21 into r,s,m;
exit when not found;
p=(m*100)/(s*100);
raise notice''Roll Nos :% '',r;
raise notice''Total : %'',m;
raise notice''Percentage:%'',p;
end loop;
close c21;
end '
language 'plpgsql';
CREATE FUNCTION

Railway Reservation Database


Consider a railway reservation Database of passengers. Passengers reserve berths of a bogie of trains. The bogie
capacity of all the bogies of a train is same.
1. TRAIN (TRAIN_NO INT, TRAIN_NAME VARCHAR(20), DEPART_TIME TIME , ARRIVAL_TIME TIME,
SOURCE_STN VARCHAR(20) , DEST_STN VARCHAR (20), NO_OF_RES_BOGIES INT , BOGIE_CAPACITY
INT)
2. PASSENGER (PASSENGER_ID INT, PASSENGER_NAME VARCHAR(20), ADDRESS VARCHAR(30), AGE
INT , GENDER CHAR) Relationship is as follows:
TRAIN _PASSENGER : M-M with descriptive attributes as follows :
TICKET ( TRAIN_NO INT , PASSENGER_ID INT, TICKET_NO INT COMPOSITE KEY, BOGIE_NO INT,
NO_OF_BERTHS INT , DATE DATE , TICKET_AMT DECIMAL(7,2),STATUS
CHAR)
The status of a particular berth can be ‘W‘ (waiting) or ‘C‘ (confirmed).
railway4=# select * from passenger;
pid | pname | addr | age | gender
-----+------------+------+-----+--------
11 | mr jadhav | abc | 20 | male
22 | mr patil | xyz | 30 | male
33 | mrs patil | xyz | 40 | female
44 | mrs jadhav | sty | 50 | female
(4 rows)

railway4=# select * from ticket;


tno | pid | ticket_no | b_no | no_berths | date | ticket_amt | status
| da
-----+-----+-----------+------+-----------+------------+------------+--------
+------------
101 | 11 | 1 | 12 | 5 | 2009-05-03 | | |
102 | 22 | 2 | 15 | 3 | 2009-04-02 | | |
104 | 44 | 5 | 12 | 5 | 2010-05-03 | 4000.00 | w |
102 | 22 | 6 | 12 | 5 | 2010-03-03 | 4000.00 | w |
103 | 33 | 4 | 12 | 5 | 2010-05-03 | 2000.00 | c |
2010-05-03
101 | 11 | 3 | 12 | 5 | 2010-05-03 | 2500.00 | w |
(6 rows)

railway4=# select * from train;


tno | tname | d_time | a_time | s_stin | dest_stin | no_of_bogies
| bogies_capacity
-----+-----------------+----------+----------+--------+-----------
+--------------+-----------------
101 | chennai express | 11:00:00 | 21:30:00 | abc | xyz | 12
| 45
102 | mumbai express | 12:00:00 | 21:30:00 | def | pqr | 20
| 60
103 | pune express | 12:00:00 | 22:30:00 | jkl | stu | 30
| 60
104 | express | 12:00:00 | 22:30:00 | mno | ghi | 40
| 80
(4 rows)

Using railway reservation database


a) Write a stored function using cursors to find the confirmed bookings of all the trains on 18-05-2009
create function fu1()returns void as '
declare cf1 cursor for select pname from passenger where pid in(select pid from
ticket where da=''2010-05-03'' and status=''c'');
paname char(20);
begin
open cf1;
loop
fetch cf1 into paname;
exit when not found;
raise notice ''Passenger Name: %'',paname;
end loop;
close cf1;
end '
language 'plpgsql';
CREATE FUNCTION

b) Write a stored function using cursors to find the total number of berths not reserved for all the trains on 18-05-2009.
create function fu4()returns void as '
declare cf2 cursor for select count(pname) from passenger where pid in(select
pid from ticket where date=''2010-05-03'' and status=''w'');
cnt int;
begin
open cf2;
loop
fetch cf2 into cnt;
exit when not found;
raise notice ''Total: %'',cnt;
end loop;
close cf2;
end '
language 'plpgsql';
CREATE FUNCTION

Bus transport Database


Consider the following Database of Bus transport system . Many buses run on one route. Drivers are allotted to the
buses shiftwise.
Following are the tables:
BUS (BUS_NO INT , CAPACITY INT , DEPOT_NAME VARCHAR(20)) ROUTE (ROUTE_NO INT, SOURCE
CHAR(20), DESTINATION CHAR(20), NO_OF_STATIONS INT)
DRIVER (DRIVER_NO INT , DRIVER_NAME CHAR(20), LICENSE_NO INT, ADDRESS CHAR(20), D_AGE
INT , SALARY FLOAT)
The relationships are as follows: BUS_ROUTE : M-1
BUS_DRIVER : M-M with descriptive attributes Date of duty allotted and Shift — it can be 1(Morning) or 2 ( Evening
).
Constraints :1. License_no is unique. 2. Bus capacity is not null.
select * from bd
buss4-# ;
bno | dno | duty_date | shift
-----+-----+------------+-------
11 | 1 | 2009-05-03 | m
22 | 2 | 2009-04-03 | e
33 | 3 | 2009-03-03 | m
(3 rows)

buss4=# select * from bus;


bno | capacity | dname | rno
-----+----------+------------+-----
11 | 40 | shivam | 101
22 | 30 | shivshakti | 102
33 | 50 | shiv | 103
(3 rows)

buss4=# select * from driver;


dno | dname | licenes_no | addr | d_age | salary
-----+-----------+------------+----------------------+-------+--------
1 | darshan | 100 | aba | 30 | 2000
2 | vidya | 200 | abb | 20 | 4000
3 | vidyadhar | 300 | bbb | 40 | 5000
(3 rows)

buss4=# select * from route;


rno | source | destination | no_of_stations
-----+----------------------+----------------------+----------------
101 | xyz | abc | 2
102 | pqr | efg | 3
103 | uvw | hij | 5
(3 rows)

Using bus driver database


a) Write a stored function using cursors to display the details of a driver, (Accept driver name as input parameter).
create function e1(dname varchar(20))returns void as '
declare e11 cursor for select dname,licenes_no,salary from driver;
n varchar(20);
l int;
s float;
begin
open e11;
loop
fetch e11 into n,l,s;
exit when not found;
raise notice''Driver Name:%'',n;
raise notice''Licenes Nos:%'',l;
raise notice''Salary:%'',s;
end loop;
close e11;
end '
language 'plpgsql';
CREATE FUNCTION
b) Write a stored function using cursors to display the details of the buses that run on routes 1,2 (Use two different
cursors for route_no = 1 and route_no = 2).

create function e2()returns void as '


declare e21 cursor for select source,destination from route where rno=101;
declare e22 cursor for select source,destination from route where rno=102;
s char(20);
d char(20);
sa char(20);
da char(20);
begin
open e21;
loop
fetch e21 into s,d;
exit when not found;
raise notice''Source:%'',s;
raise notice''Destination:%'',d;
end loop;
close e21;
open e22;
loop
fetch e22 into sa,da;
exit when not found;
raise notice''Source:%'',sa;
raise notice''Destinatio:%'',da;
end loop;
close e22;
end '
language 'plpgsql';
CREATE FUNCTION

Assignment 4 : Handling errors and Exceptions


SET A
Using Bank Database
a) Write a stored function to print the total number of customers of a particular branch. ( Accept branch name as input
parameter.) In case the branch name is invalid, raise an exception for the same.

create or replace function f1(nm varchar(30))returns text as '


declare rec record;
cnt int;
begin
for rec in select * from branch
loop
if(rec.bname<>nm)then
raise notice''Invalid'';
else
select count(cno) into cnt from bcl where bid in(select bid from branch where
rec.bname=nm);
end if;
end loop;
raise notice''customer count is : %'',cnt;
return'' '';
end '
language 'plpgsql';

CREATE FUNCTION
b) Write a stored function to increase the loan approved amount for all loans by 20%. In case the initial loan approved
amount was less than Rs 10000, then print a notice to the user, before updating the amount .

create or replace function f2()returns text as'


declare rec record;
begin
for rec in select * from la
loop
if(rec.appmoney<''$10000'')then
raise notice ''amount is less than 10000 '';
else
update la set appmoney=appmoney+(appmoney*0.2)where lano=rec.lano;
end if;
end loop;
return '''';
end'
language'plpgsql';
CREATE FUNCTION

SET B

Using Project-Employee database

create table project(pno int primary key,pname varchar(15),ptype varchar(15),duration


int);
CREATE TABLE

create table emp(eno int primary key,ename varchar(15),j_date date);


CREATE TABLE

create table prog_emp(pno int references project(pno),eno int references


emp(eno),s_date date);
CREATE TABLE

insert into project values(1,'system','computer',100);

insert into project values(2,'robotics','computer',100);


insert into project values(3,'cloud network','computer',50);
insert into project values(4,'microprocessor','electronics',150);
insert into project values(5,'eye senser','electronics',250);
insert into project values(6,'remote car','meachinical',75);

insert into emp values(1,'anil','04-04-2010');

insert into emp values(2,'ajay','05-23-2010');

insert into emp values(3,'nadim','08-18-2011');

insert into emp values(4,'samadhan','12-28-2012');

insert into emp values(5,'mahesh','12-28-2012');

insert into prog_emp values(1,1,'04-04-2010');

insert into prog_emp values(1,2,'05-23-2010');

insert into prog_emp values(2,2,'05-20-2010');

insert into prog_emp values(3,1,'04-25-2011');

insert into prog_emp values(3,1,'03-25-2011');

insert into prog_emp values(3,4,'02-12-2012');


insert into prog_emp values(4,5,'05-12-2013');

a) Write a stored function to accept project name as input and print the names of employees working on the project. Also
print the total number of employees working on that project. Raise an exception for an invalid project name.
create function SetA_a(varchar ) returns integer as $$
declare
rec record;
cur cursor for select * from project,prog_emp,emp where project.pno=prog_emp.pno and
emp.eno=prog_emp.eno;
cnt integer:=0;
name alias for $1;
begin
open cur;
loop
fetch cur into rec;
exit when not found;
if rec.pname=name then
raise notice '%',rec.ename;
cnt:=cnt+1;
end if;
end loop;
if cnt=0 then
raise exception 'Invalid Project name';
end if;
close cur;
return cnt;
end;
$$ language plpgsql;
CREATE FUNCTION

b) Write a stored function to decrease the Hours_worked by 2 hours, for all projects in which employees from department
no 2 is working. Raise an exception , in case the hours_worked becomes = 0 , after updation.
project4=# create or replace function f3() returns text as'
declare rec record;
n int;
begin
select hours into n from pe where pno in(select pno from project where
pname=''Electronics'');
update pe set hours=hours-2 where pno in(select pno from project where
pname=''Electronics'');
if(n-2=0)then
raise notice''hours are 0'';
end if;
raise notice''number : %'',n;
return'' '';
end'
language 'plpgsql';
CREATE FUNCTION

SET C
Using Bus transport Database
a) Write a stored function to print the names of drivers working on both shifts on ‘20/04/2014’.

create or replace function f4(d date) returns text as'


declare
rec record;
nm driver.dname%type;
begin
for rec in select * from bd
loop
if(rec.duty_date<>d)then
raise notice''Date Is Invalid'';
else
select dname into nm from driver where dno in(select dno from bd where
shift=''m'' and shift=''e'' and duty_date=d);
end if;
end loop;
raise notice''dname=%'',nm;
return'' '';
end'
language 'plpgsql';
CREATE FUNCTION

b) Write a stored function to accept the bus_no and date and print its allotted drivers. Raise an exception in case of
invalid bus number.

Assignment 5 : Triggers.
SET A
Using Item_supplier Database
Item(itemno integer,Itemname varchar(20),quantity integer) Supplier(SupplierNo,Supplier name,address,city)
Item_sup(item_no integer ,Supplier_no integer,Rate Money)
Item and supplier are related with many to many relationship .Rate is descriptive attribute.
a. Write a trigger before update on rate field, If the difference in the old rate and new rate to be entered is more than Rs
2000/ . Raise an exception and display the corresponding message

supplier4=# select * from item;


ino | iname | quantity
-----+------+---------
101 | ABC | 100
102 | DEF | 150
103 | GHI | 50
104 | JKL | 250
105 | MNO | 200
(5 rows)

supplier4=# select * from supplier;


sno | sname | address | city
-----+-----------+---------+-----
1 | Shiva | Kothrud | Pune
2 | Darshan | Bibewadi | Pune
3 | Vidhyadhar | Katraj | Pune
(3 rows)

supplier4=# select * from itemsupplier


supplier4-# ;
ino | sno | rate
-----+----+----------
101 | 1 | $1,000.00
101 | 1 | $2,000.00
102 | 1 | $1,500.00
103 | 2 | $2,500.00
104 | 2 | $500.00
105 | 3 | $1,500.00
(6 rows)
--------------------------------------------------------------------------
1)

create or replace function a1() returns trigger as '


begin
if(new.rate-old.rate)>''$2000'' then
raise exception''Difference Should B Less Then $2000 % '',new;
end if;return new;
end '
language 'plpgsql';
CREATE FUNCTION

supplier4=# create trigger t3 before insert or update on itemsupplier for each


row execute procedure a1();
CREATE TRIGGER

supplier4=# update itemsupplier set rate='$6000' where ino=104;


ERROR: Difference Should B Less Then $2000 (104,2,"$6,000.00")

supplier4=# update itemsupplier set rate='$2000' where ino=105;


UPDATE 1

b. Write a trigger before insert or update on rate field, If the rate to be entered is zero then. Raise an exception and
display the message “Zero rate not allowed”.
2)

supplier4=# create or replace function a2() returns trigger as '


begin
if(new.rate =''$0'') then
raise exception''Rate Should Not Be Zero %'',new;
end if;return new;
end '
language 'plpgsql';
CREATE FUNCTION

supplier4=# create trigger T11 before insert or update on itemsupplier for each
row execute procedure a2();
CREATE TRIGGER

supplier4=# insert into itemsupplier values(101,1,'$0');


ERROR: Rate Should Not Be Zero (101,1,$0.00)

SET B
Student –Marks database
Student (rollno integer,name varchar(30),address varchar(50),class varchar(10)) Subject(Scode varchar(10),subject
name varchar(20))
student and subject are related with M-M relationship with attributes marks scored.
a) Write a trigger before deleting a student record from the student table. Raise a notice and display the message
“student record is being deleted”

create table student(rno int primary key,name varchar(20),city varchar(20),class


varchar(10));
CREATE TABLE

create table subject(scode varchar(10) primary key, sname varchar(20));


CREATE TABLE
create table stud_sub(rno int references student(rno), scode varchar(20) references
subject(scode), marks int);
CREATE TABLE

insert into student values(1,'abcd','pune','fybcs');


insert into subject values('CS101','c prog');
insert into stud_sub values(1,'CS101',50);

create function ass5C_1() returns trigger as $$


begin
if new.marks<0 then
raise exception 'Invalid Marks';
end if;
return new;
end;
$$ language plpgsql;

create trigger ass5C_1 before insert or update on stud_sub for each row execute
procedure ass5C_1();
CREATE TRIGGER

create function ass5c_2() returns trigger as $$


begin
if old.city='pune' then
raise exception 'Student record can not be deleted';
end if;
return old;
end;
$$ language plpgsql;

create trigger ass5c_2 before delete on student for each row execute procedure
ass5c_2();

b) Write a trigger to ensure that the marks entered for a student, with respect to a subject is never < 10 and greater than
100.
student4=# create or replace function f6() returns trigger as '
begin
if new.marks<10 new.marks="" or="">100 then
raise exception'' Invalid %'',new;
end if;
return new;
end '
language 'plpgsql';
CREATE FUNCTION

student4=# create trigger t4 before insert or update on ss for each row execute
procedure f6();
CREATE TRIGGER

student4=# insert into ss values(105,4,91);


INSERT 0 1

student4=# insert into ss values(105,4,09);


ERROR: Invalid (105,4,9)

SET C
News paper database
Newspaper(name varchar(20), language varchar(20),Publisher varchar(20),cost money) Cities(pincode varchar(6), city
varchar(20), state varchar(20))
Newspaper & Cities M to M relationship with descriptive attribute daily_required integer
a) Calculate the length of pincode. Write a trigger which will fire before insert on the cities table which check that the
pincode must be of 6 digit. If it is more or less then it display the appropriate message.

postgres=# create database paper4


postgres-# ;
CREATE DATABASE
postgres=# create table newspaper(name varchar(20) primary key,language
varchar(20),publisher varchar(20),cost money);
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "newspaper_pkey"
for table "newspaper"
CREATE TABLE
postgres=# create table cities(pincode varchar(6) primary key,city
varchar(20),state varchar(20));
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "cities_pkey" for
table "cities"
CREATE TABLE
postgres=# create table n_c(name varchar(20) references newspaper(name) on
delete cascade,pincode varchar(6) references cities(pincode) on delete
cascade,daily_req int);
CREATE TABLE

postgres=# insert into newspaper values('Sakal','Marathi','Sakal','$2');


INSERT 0 1
postgres=# insert into newspaper values('Today','Marathi','Sakal','$2');
INSERT 0 1
postgres=# insert into newspaper values('XYZ','English','Abc','$5');
INSERT 0 1
postgres=# insert into cities values('411002','Pune','Maharashtra');
INSERT 0 1
postgres=# insert into cities values('422020','Nashik','Maharashtra');
INSERT 0 1
postgres=# insert into cities values('455020','XYZ','Kolkata');
INSERT 0 1
postgres=# insert into n_c values('Sakal','411002',5000);
INSERT 0 1
postgres=# insert into n_c values('Today','422020',500);
INSERT 0 1
postgres=# insert into n_c values('XYZ','455020',500);
INSERT 0 1
postgres=# select * from newspaper;
name | language | publisher | cost
-------+----------+-----------+-------
Sakal | Marathi | Sakal | $2.00
Today | Marathi | Sakal | $2.00
XYZ | English | Abc | $5.00
(3 rows)

postgres=# select * from cities;


pincode | city | state
---------+--------+-------------
411002 | Pune | Maharashtra
422020 | Nashik | Maharashtra
455020 | XYZ | Kolkata
(3 rows)

postgres=# select * from n_c;


name | pincode | daily_req
-------+---------+-----------
Sakal | 411002 | 5000
Today | 422020 | 500
XYZ | 455020 | 500
(3 rows)

1)

create or replace function t11()returns trigger as '


begin
if length(new.pincode)<6 length="" new.pincode="" or="">6 then
raise exception ''Incorrect Pincode %'',new;
end if;
return new;
end '
language 'plpgsql';
CREATE FUNCTION

create trigger t1 before insert on cities for each row execute procedure t11();
CREATE TRIGGER

paper4=# insert into cities values('41101','Solapur','Maharashtra');


ERROR: Incorrect Pincode (41101,Solapur,Maharashtra)

paper4=# insert into cities values('411012','Solapur','Maharashtra');


INSERT 0 1

paper4=# insert into cities values('4110121','Solapur','Maharashtra');


ERROR: value too long for type character varying(6)

b) Write a trigger which will prevent deleting cities from Maharatra state.

2)

paper4=# create or replace function t12()returns trigger as '


begin
if old.state=''Maharashtra'' then
raise exception ''Cant Delete %'',old;
end if;
return old;
end '
language 'plpgsql';
CREATE FUNCTION
^
paper4=# create trigger t2 before delete on cities for each row execute
procedure t12();
CREATE TRIGGER

paper4=# select * from cities;


pincode | city | state
---------+---------+-------------
411002 | Pune | Maharashtra
422020 | Nashik | Maharashtra
455020 | XYZ | Kolkata
411012 | Solapur | Maharashtra
(4 rows)

paper4=# delete from cities where state='Maharashtra';


ERROR: Cant Delete (411002,Pune,Maharashtra)

paper4=# delete from cities where state='Kolkata';


DELETE 1

SET D
Using Railway Reservation Database
a) create a trigger to validate train arrival time must be less than train departure time.
railway4=# create or replace function t1()returns trigger as '
begin
if new.a_time
raise exception ''correct time %'',new;
end if;
return new;
end '
language 'plpgsql';
CREATE FUNCTION

create trigger t2 before insert or update on train for each row


execute procedure t1();
CREATE TRIGGER

railway4=# insert into train values(105,'Kanyakumari


express','20:00:00','18:00:00','aaa','xxx',12,60);
INSERT 0 1
railway4=# insert into train values(106,'Kanyakumari
express','12:00:00','18:00:00','aaa','xxx',12,60);
ERROR: arrival time 18:00:00 should be less than departure time

b) Write a trigger which will be activated before changing the status field in the ticket table and print a message to the
user.
railway4=# create or replace function f1() returns trigger as'
begin
if old.status!=new.status then
raise exception ''Cannot change status %'',old;
end if;
return old;
end
'
language 'plpgsql';
CREATE FUNCTION
railway4=# create trigger t before insert or update on ticket for each row
execute procedure f1();
CREATE TRIGGER
railway4=# update ticket set status='c' where tno=104;
ERROR: Cannot change status (104,44,5,12,5,2010-05-03,4000.00,w,)
railway4=# update ticket set status='w' where tno=104;
UPDATE 1

SET E
Using Bus Transportation database
a) Define a trigger after insert or update the record of driver if the age is between 18 and 50 give the message “valid
entry” otherwise give appropriate message.
buss4=# create or replace function agep() returns trigger as '
begin
if new.d_age<18 new.d_age="" or="">50 then
raise exception''Invalid Age % '',new;

end if; return new;


end '
language 'plpgsql';
CREATE FUNCTION

buss4=# create trigger t1 after insert or update on driver for each row execute
procedure agep();
CREATE TRIGGER

buss4=# insert into driver values(4,'ABC',400,'xyz',15,15000);


ERROR: Invalid Age (4,ABC,400,"xyz ",15,15000)

buss4=# insert into driver values(4,'ABC',400,'xyz',25,15000);


INSERT 0 1

buss4=# select * from driver;


dno | dname | licenes_no | addr | d_age | salary
-----+----------+-----------+---------------------+------+-------
1 | darshan | 100 | aba | 30 | 2000
2 | vidya | 200 | abb | 20 | 4000
3 | vidyadhar | 300 | bbb | 40 | 5000
4 | ABC | 400 | xyz | 25 | 15000
(4 rows)

buss4=# update driver set d_age=10 where dno=1;


ERROR: Invalid Age (1,darshan,100,"aba ",10,2000)

buss4=# update driver set d_age=20 where dno=1;


UPDATE 1

b) Define a trigger after delete the record of bus having capacity < 10. Display the message accordingly

2)
uss4=# create or replace function c1()returns trigger as '
begin
if old.capacity>10 then
raise exception ''invalid%'',old;
end if;
return old;
end '
language 'plpgsql';
CREATE FUNCTION
buss4=# create trigger t22 after delete on bus for each row execute procedure
c1();
CREATE TRIGGER
buss4=# insert into bus values(55,8,'abc',101);
INSERT 0 1
buss4=# select * from bus;
bno | capacity | dname | rno
-----+---------+-----------+----
22 | 30 | shivshakti | 102
33 | 50 | shiv | 103
44 | 9 | abc | 101
55 | 8 | abc | 101
(4 rows)

buss4=# delete from bus where bno=44;


DELETE 1
buss4=# delete from bus where bno=33;
ERROR: invalid(33,50,shiv,103)

You might also like