Вы находитесь на странице: 1из 40

Lab Record 1

 Create the various tables in SQL using Data Definition Language statements
and apply the given constraints on them.

1. STUDENT

Column Name Data Type Constraints


StudentID CHAR(5) Primary Key
LastName VARCHAR2(15) NOT NULL
FirstName VARCHAR2(15) NOT NULL
Street VARCHAR2(25)
City VARCHAR2(15)
State VARCHAR(2) Default ‘NJ’
Zip VARCHAR(4)
StartTerm VARCHAR(4) Foreign Key to Term(Term
ID)
Birthdate Date
FacultyID Number(3) Foreign Key to
Faculty(Faculty ID)
MajorID Number(3) Foreign Key to
Major(MajorID)
Phone Char(10)

CREATE TABLE STUDENT

StudentID CHAR(5) PRIMARY KEY,

LName VARCHAR2(15) NOT NULL,

FName VARCHAR2(15) NOT NULL,

Street VARCHAR2(25),

City VARCHAR2(15),

State VARCHAR2(2) DEFAULT 'NJ',


StartTerm VARCHAR(4),

Zip VARCHAR(5),

Birthday DATE,

FacultyID NUMBER(3),

MajorID NUMBER(3),

Phone CHAR(10)

);

ALTER TABLE STUDENT ADD FOREIGN KEY (StartTerm) references


TERM(TermID);

ALTER TABLE STUDENT ADD FOREIGN KEY (FacultyID) references


FACULTY(FacultyID);

ALTER TABLE STUDENT ADD FOREIGN KEY (MajorID) references


MAJOR(MajorID);

2. FACULTY

Column Name Data Type Constraints


FacultyID Number(3) Primary Key
Name VARCHAR2(15) NOT NULL
RoomID NUMBER(2) Foreign Key to
Location(RoomID)
Phone CHAR(13) Unique
DeptID Number(1) Foreign key to
Department (DeptID)

CREATE TABLE FACULTY


(
FacultyID NUMBER(3) PRIMARY KEY,
Name VARCHAR2(15) NOT NULL,
RoomID NUMBER(2),
Phone CHAR(3) UNIQUE,
DeptID NUMBER(1)
);
ALTER TABLE FACULTY ADD FOREIGN KEY (RoomID) references
LOCATION(RoomID);
ALTER TABLE FACULTY ADD FOREIGN KEY (DeptID) references
DEPARTMENT(DeptID);

3. CRSSECTION

Column Name Data Type Constraints


CSID Number(4) Primary Key
CourseID VARCHAR2(6) Foreign Key to
Course(CourseID) ,
NOT NULL
Section CHAR(2) Not Null
TermID CHAR(4) Foreign key to
TERM(TermID), Not
Null
FacultyID Number(3) Foreign Key to
Faculty(FacultyID)
Day VARCHAR2(2)
StartTime VARCHAR2(2)
EndTime VARCHAR2(5)
RoomID NUMBER(2) Foreign Key to
Location(RoomID)
MaxCount Number(2) Check(MaxCount>0)

CREATE TABLE CRSSECTION


(
CSID NUMBER(4) PRIMARY KEY,
CourseID VARCHAR2(6) NOT NULL,
Section CHAR(2) NOT NULL,
TermID CHAR(4) NOT NULL,
FacultyID NUMBER(3),
Day VARCHAR2(2),
StartTime VARCHAR2(5),
EndTime VARCHAR2(5),
RoomID NUMBER(2),
MaxCount NUMBER(2) Check(MaxCount>0)
);
ALTER TABLE CRSSECTION ADD FOREIGN KEY(CourseID) references
COURSE(CourseID);
ALTER TABLE CRSSECTION ADD FOREIGN KEY(TermID) references
TERM(TermID);
ALTER TABLE CRSSECTION ADD FOREIGN KEY(FacultyID) references
FACULTY(FacultyID);
ALTER TABLE CRSSECTION ADD FOREIGN KEY(RoomID) references
ROOM(RoomID);

4. COURSE

Column Name Data Type Constraints


CourseID VARCHAR2(6) Primary Key
Title VARCHAR2(20) Unique
Credits Number(1) Check(Credits>0
AND Credits<=4)
PreReq VARCHAR2(6) Foreign Key to
Course(CourseID)

CREATE TABLE COURSE

CourseID VARCHAR2(6) PRIMARY KEY,

Title VARCHAR2(20) Unique,

Credits NUMBER(1) Check(Credits>=0 and Credits<=4),

PreReq VARCHAR2(6)

);

ALTER TABLE COURSE ADD FOREIGN KEY(PreReq) references


COURSE(CourseID);
5. REGESTRATION

Column Name Data Type Constraints

StudentID CHAR(5) Composite Primary Key,


FK to Student(StudentID)
CSID Number(4) Composite Primary Key,
FK to CRSSECTION(SID)
MidTerm CHAR Check(MidTerm
in(‘A’,’B’,’C’,’D’,’F’,’W’))
Final CHAR Check(Final
in(‘A’,’B’,’C’,’D’,’F’,’W’))
RegStatus CHAR Check(Final in(‘X’,’R’,’W’))

CREATE TABLE REGESTRATION

StudentID CHAR(5),

CSID NUMBER(4),

MidTerm CHAR Check(MidTerm in('A','B','C','D','F','W')),

Final CHAR Check (Final in('A','B','C','D','F','W')),

PRIMARY KEY(StudentID,CSID)

);
6. ROOM
Column Name Data Type Constraints
Room Type CHAR Primary Key
Room Desc VARCHAR2(9)

CREATE TABLE ROOM

RoomType CHAR PRIMARY KEY,

RoomDesc VARCHAR2(9)

);
7. LOCATION

Column Name Data Type Constraints


RoomID Number(2) Primary Key
Building VARCHAR2(7) Not Null
RoomNo CHAR(3) Not Null,Unique
Capacity Number(2) Check(Capacity>0)
RoomType CHAR Foreign Key to
Room(RoomType)

CREATE TABLE LOCATION


(
RoomID NUMBER(2) PRIMARY KEY,
Building VARCHAR2(7) Not Null,
RoomNo CHAR(3) Not Null Unique,
Capacity NUMBER(2) Check(Capacity>0),
RoomType CHAR
);
ALTER TABLE LOCATION ADD FOREIGN KEY(RoomType) references
ROOM(RoomType);

8. TERM
Column Name Data Type Constraints
TermID CHAR(4) Primary Key
TermDesc VARCHAR2(11)
StartDate Date
EndDAte Date

CREATE TABLE TERM


(
TermID CHAR(4) PRIMARY KEY,
TermDesc VARCHAR2(11),
StartDate DATE,
EndDate DATE
);
9. DEPARTMENT

Column Name Data Type Constraints


DeptID Number(1) Primary Key
DeptName VARCHAR2(20)
FacultyID NUMBER(3) Foreign Key to
Faculty(FacultyID)

CREATE TABLE DEPARTMENT


(
DeptID NUMBER(1) PRIMARY KEY,
DeptName VARCHAR2(20),
FacultyID NUMBER(3)
);
ALTER TABLE DEPARTMENT ADD FOREIGN KEY(FacultyID) references
FACULTY(FacultyID);

10. MAJOR

Column Name Data Type Constraints


MajorID NUMBER(3) Primary Key
MajorDesc VARCHAR2(25)

CREATE TABLE MAJOR

MajorID NUMBER(3) PRIMARY KEY,

MajorDesc VARCHAR2(25)

);
Lab Record 2

 Display all employee names (Last and First) separated by a


comma and a space with proper case , and salary with
currency format.

SELECT LName ||','|| FName, TO_CHAR(Salary,'$999,999') from


Employee;

 Display all employees with their commission value. Display 0


commission for employees who do not get any commission.

SELECT LName , FName, NVL(Commission,0) from Employee;

 Find The highest and lowest Salary for employees.

SELECT Max(Salary),Min(Salary) from Employee;

 Count the total number of rooms in location.

SELECT Count(RoomNo) from Location;

 Count the distinct building names in location.

SELECT count(DistinctBuilding) from Location;

 Display all student names and birth dates with format '20
October 1970'.

SELECT FName,LName, TO_CHAR(BirthDate,'DD,MONTH,YYYY')from


student;
 Find Average age for students.

SELECT AVG (Extract(year from SysDate)-Extract(year from


BirthDate)) from Student;

 find 2 to the power 10.

SELECT power(2,10) from Dual;

 Find sum of maximum count by term by course (grouped by 2


columns).
SELECT Sum(MaxCount) from CRSSection GROUP BY (TermID,CourseID);

 Count number of faculty members by each department.

SELECT Count(FacultyID),DeptID from faculty Group By DeptID;

 Display only the year value from each employee's HireDate.'

SELECT Extract(year from HireDate) from Employee;

 Find average employee commission


a- ignore Null , b-Do not ignore Null:

SELECT
Avg(COALESCE(Commission,0)),AVG(NVL(COALESCE(Commission,0))) FROM
Employee

 Display the total number of dependents for each employee who


have at least 2 students.
SELECT E.EmployeeID,Count(D.DependentID) from Employee E,
Dependent D where (E.EmployeeID=D.EmployeeID and
count(D.DependentID)>=2);

 Find the students who are born in May.

SELECT StudentID, FName, LName, Extract(Month from


BirthDate) as BirthMonth from Student where
(BirthMonth='May');

 Display Employees last name and first name followed by


salary +commission if commission is not null else display
salary only.
SELECT EmployeeID, FName ||' '|| LName as FullName , Salary
+NVL(comission,0) as TotalSalary from Employee;
Lab Record 3

1. Display all employees names and their department names.

SELECT LName, FName, DeptName from Employee e, Dept d where


e.DeptID=d.DeptID;

2. Find names of the supervisor for employee number 433.


SELECT f.FName ||' 'F.LName as EmployeeName from Employee
e,Employee f where e.EmployeeID=433 and F.employeeID=e.Suprevisor;

3. Find all employees full names with salary and their


supervisor’s' name with his salary.
SELECT e.Fname||' '||e.LName as EmployeeName,e.Salary,
f.FName||' '||f.LName as SupName, f.Salary from employee f ,
Employee e where f.EmployeeID=e.Suprevisor;

4. Find each employee salary information and level based on the


salary.
SELECT e.FName||' '||e.LName as EmployeeName,e.salary, LevelNo
from Employee e,EmpLevel l where e.salary>l.LowSalary and
e.Salary<l.HighSalary;

5. Display each employee name, department name, position


description and qualification description.

SELECT FName||' '||LName as name, d.DeptName, P.PosDesc,


q.QualDesc from Employee e, Dept d, Position p, Qualification
q where e.DeptID=d.DeptID and e.POsitionID = p.POsitionID and
e.QualID = q.QualID;
6. Find all employees in the sales department.

SELECT e.FName||' '|| e.LName as Name from Employee e, Dept d


where e.DeptID=d.DeptID and d.DeptName='sales';

7. Display employee names and dependent information using Outer


Join.
SELECT e.FName||' '||e.LName as name , d.Depdob, d.relation from
Employee e, Dependent d where e.EmployeeID=d.EmployeeID order by
name;

8. Find out the names and number of years worked along with
their department names in descending order by number of
years worked.
SELECT e.fname||' '|| e.lname as name, extract( year from
sysdate )- extract(year from e.hiredate) as years-worked,
d.deptname from employee e, dept d where e.deptid=d.deptid
order by years-worked desc;

9. Display a student full name along with his major


description.

SELECT s.FName||' '||s.LName as StuName, m.MajorDesc from


Student s, Major m where s.MajorID=m.MajorID;

10. Get names of students, who received final grade 'F' in


winter 2003.
SELECT s.FName||' '||s.LName as StuName from Student s,
registration r where (s.StartTerm=(select TermID from term where
TermDesc='Winter 2003') and s.StudentID=r.StudentID and
r.final="F");
11. Get Spring 2003 course sections with the faculty member
assigned to teach the class include course sections without
any faculty assigned to them.

SELECT c.Section,f.Name as faculty from CRSSection c, Faculty


f where c.FacultyID=f.FacultyID and c.TermID=(select TermID
from Term where TermDesc='Spring 2003') UNION select section
from CRSSection where FacultyID is NULL;

12. Display Course titles along with their prerequisite names.


Also display courses without prerequisite .

SELECT c.Title as CourseTitle , p.Title as PreReqTitle from


Course c, Course p where c.PreReq = d.CourseID Union Select
Title, NVL(PreReq,'NVL') from course where PreReq is NULL;
Lab Record 4
1. Display Employee "Tinku Shaw" department name.

SELECT DeptName from dept where DeptID=(SELECT DeptID from


Employee where FName||' '||LName='Jinku Shaw');

2. Display the employee's name with maximum salary.'

SELECT FName||' 'LName, Salary from Employee where


Salary=(SELECT max(Salary) from Employee);

3. Who has qualification as John Smith.

SELECT FName||" "||LName as EmpName from Employee where


QualID=(SELECT QualID from Employee where FName||'
'LName="John Smith");

4. Display Student "Jose Diaz" faculty name and phone number.


SELECT name, phone from faculty where FacultyID=(SELECT
FacultyID from Student where FName||' '||LName="Jose Diaz");

5. Which department has more employees than department 20.


SELECT DeptName, DeptID from Dept where DeptID=(SELECT DeptID
from Employee GROUP BY DeptID HAVING COUNT(EmployeeID>(SELECT
count(EmployeeID) from Emploee where DeptID=20));

6. Find Employees with minimum Salary in their own department


with the use of correlated subquery.
SELECT FName||' '||LName as EmpName, Salary from Employee e1
where Salary=(SELECT MIN(Salary) from Emploee e2 where
e1.DeptID=e2.DeptID);
Lab Record 5

1. Create a view to include all employee information, but hide


salary & commission.

Create view emp as SELECT EmployeeID, LNamem, FName,


PositionID, SuprevisorID, HireDate, DeptID, QualID from
Employee;

2. Create a view to include department name and average salary


by department.

Create view deptview1 as select d.deptname, avg(e.salary) as


average-salary from employee e, dept d where d.deptid=e.deptid
group by(deptname);

3. Create a view that will display name, department number, and


total income of each employee in department 10.

CREATE VIEW deptview2 as select e.lname||' '||e.fname as


name, (e.salary+NVL(e.commission,0)) as total income from
employee e, dept d where d.deptid=10;

Lab Record 6

1. Write a PL/SQL block to swap the value of 2 variables. Print


variables before and after swapping.

DECLARE

a number(5)

b number(5)

temp number(6)

BEGIN

DBMS-OUTPUT.PUT_LINE(' Enter the values');

a:=&a;

b:=&b;

DBMS-OUTPUT.PUT_LINE(' Values before swapping : ');

DBMS-OUTPUT.PUT_LINE(a);

DBMS-OUTPUT.PUT_LINE(b);

temp:=a; a:=b; b:=temp;

DBMS-OUTPUT.PUT_LINE(' Values after swapping : ');

DBMS-OUTPUT.PUT_LINE(a);

DBMS-OUTPUT.PUT_LINE(b);

END;

2. Write a PL/SQL program with 2 variables for the first name


and the last name. Print the full name with last name
seperated by a comma and a space.
DECLARE

a varchar(20);

b varchar(20);

BEGIN

DBMS-OUTPUT.PUT_LINE('Enter the first name');

a:='&a';

DBMS-OUTPUT.PUT_LINE('Enter the last name');

b:='&b';

DBMS-OUTPUT.PUT_LINE(b||' , '||a);

END;

3. Write a PL/SQL block to find out if a year is a leap. A leap


year is divisible by 4, bot not divisible by 100 OR it is
divisible by 400.

DECLARE

a number(4);

BEGIN

DBMS-OUTPUT.PUT_LINE('Enter the year');

a:='&a';

if(mod(a,4)=0 and mod(a,100)!=0) OR (mod(a,400)=0) then

DBMS-OUTPUT.PUT_LINE('The year is leap');

END IF;

END;
4. Using for loop, print the values 10 to 1 in reverse order.

BEGIN

for i in reverse 1.10

loop

DBMS-OUTPUT.PUT_LINE(i);

END LOOP;

END;

5. Write a PL/SQL block to calculate the sum of digits of a


given number.

DECLARE

input integer(10):=&input;

temp1 integer(10);

temp2 integer(10);

BEGIN

temp2:=0;

while input>0

loop

temp1:=input mod 10;

temp2:=temp1+temp2;

input:=floor(input/10);

end loop;

DBMS-OUTPUT.PUT_LINE('The sum of digits is'||temp2);

END;
6. Write a PL/SQL block to check whether a number n is prime
number or not.

DECLARE

n number;

i number;

prime number;

BEGIN

i=2;

prime:=1;

n:=&n;

for i in 2..n/2

loop

if mod(n,i)=0 then

prime:=0

end if;

end loop;

if flag=1 then

DBMS-OUTPUT.PUT_LINE('Prime');

else

DBMS-OUTPUT.PUT_LINE('Not Prime');

end if;

END;
7. Write a PL/SQL block to check whether an input integer is
perfect number or not.

DECLARE

n number;

i number;

perfect number;

BEGIN

n=&n;

perfect:=0;

for i in 1..n/2

loop

if mod(n,i)=0 then

perfect:=perfect+1;

end if;

end loop;

if n=perfect then

DBMS-OUTPUT.PUT_LINE('Perfect');

else

DBMS-OUTPUT.PUT_LINE('Not Perfect');

end if;

END;
8. Write a PL/SQL block to print the first n numbers of a
Fibonacci sequence.

DECLARE

first number:=0;

second number:=1;

third number;

n number:=&n;

i number;

BEGIN

DBMS-OUTPUT.PUT_LINE('Fibonacci Series is : ');

DBMS-OUTPUT.PUT_LINE(first);

DBMS-OUTPUT.PUT_LINE(second);

for i in 2..n

loop

third=first+second;

DBMS-OUTPUT.PUT_LINE(third);

first:=second;

second:=third;

end loop;

END;
9. Write a PL/SQL block to check the given String is Palindrome
or not.

DECLARE

len number;

str Varchar(20):='&input_string';

chkstr VARCHAR2(20);

BEGIN

len:=length(str);

for i in reverse 1..len

loop

chkstr:=chkstr||substr(str,i,1);

end loop;

if chkstr= str then

DBMS-OUTPUT.PUT_LINE(str||" is a Plaindrome");

else

DBMS-OUTPUT.PUT_LINE(str||" is not a Plaindrome");

End IF;

END;
Lab Record 7

1. Create a PL/SQL block to declare a cursor to select last


name, first name, salary and hire date from that employee
table. Retrieve each row from cursor and print the employees
information if the employee’s salary is greater than 5000
and hire date is before 31-Dec-1997.

DECLARE
cursor csr is select lname,fname, salary, hiredate, from employee;

BEGIN
for i in csr then

loop

if (i.salary>50000 and i.hiredate<to-date('31'-Dec-1997,'DD-Mon-YY')


then

DBMS-OUTPUT.Put_line(i.lname||' '||i.fname||' '||i.salary||' '||i.hiredate);

end if;

end loop;

END;

2. Create a PL/SQL block to declare a cursor to select last


name, first name, salary from employee table and department
name and location from dept where deptid=20;

DECLARE
CURSOR CSR is select(name, fname, salary, deptname,location,e.deptid
from employee e, dept d where e.deptid=d.deptid);

BEGIN

for i in CSR

loop

if (i.deptid=20) then
DBMS-OUTPUT.PUT_LINE(i.lname||' '||i.fname||' '||i.salary||' '||i.deptname||'
'||i.location);

end if;

end loop;

END;
3. CREATE a PL/SQL block that declares a cursor to pass a
parameter to the cursor data of the type that is same as the
salary column in employee retrieve information into the
cursor for a salary higher than parameter value. Use a loop
to print each employee information for the cursor.

DECLARE

CURSOR CSR(sal employee.salary%type) is select * from


employee where salary>sal;

EmpRow employee%rowtype;

salary employee.salary%type;

BEGIN

salary:=salary;

OPEN CSR(salary);

loop

fetch CSR into emprow;

exit when csr%NOTFOUND;

DBMS-OUTPUT.PUT_LINE(employee.lname||' '||emprow.fname||'
'||emprow.positionid||' '||emprow.suprevisorid||'
'||emprow.hiredate||' '||emprow.salary||'
'||emprow.commisiion||' '||emprow.deptid);

end loop;

CLOSE CSR;

END;
Lab Record 8

1.Write a trigger that is fired before the DML statement’s


execution on the EMPLOYEE table. The trigger checks the day based
on SYSDATE. If the day is Sunday, the trigger does not allow the
DML statement’s execution and raises an exception. Write the
appropriate message in the exception-handling section.

CREATE OR REPLACE TRIGGER Emp_Trig BEFORE INSERT OR UPDATE ON


EMPLOYEE FOR EACH ROW WHEN(trim(TO_CHAR(SYSDATE,'DAY'))='MONDAY')

BEGIN
raise_application_error(-20000,"Can't perform DML on Monday");

End;

INSERT INTO EMPLOYEE Values (23, 'S', 'J', 1, NULL,


TO_DATE('04/15/1960 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 265000,
35000, 10, 1);

2.Write a trigger that is fired after an INSERT statement is


executed for the STUDENT table. The trigger writes the new
student’s ID, user’s name, and system’s date in a table called
TRACKING. (Note: You must create the TRACKING table first).

CREATE OR REPLACE TRIGGER Stud_Trig AFTER INSERT ON STUDENT FOR


EACH ROW

DECLARE

UName VARCHAR2(30);

NewDate DATE;
BEGIN

SELECT USER INTO UName FROM DUAL;

SELECT SYSDATE INTO NewDate FROM DUAL;

INSERT INTO TRACKING VALUES(:NEW.StudentID, UName, NewDate);

END;

INSERT INTO STUDENT VALUES(13,'DIAZ','JOSE','1 FORD AVENUE


#7','HILL','NJ',08863,'WN03','12-JAN-83','123','100',9735551111);

3.Create a complex view EMP_DEP_VIEW using an outer join between


EMPLOYEE and DEPENDENT table with employee names, dependent’s
birthdate and relation. The outer join will also return employees
without any dependents. Now, create an INSTEAD OF trigger based
on EMP_DEP_VIEW to enable you to delete employee 433 through
view.

Create view EMP_DEP_VIEW as select e.employeeid, e.lname,


e.fname, d.depdob, d.relation from employee e, dependent d where
e.employeeid = d.employeeid(+);

CREATE OR REPLACE TRIGGER Emp_Del_Trig INSTEAD OF DELETE ON


EmpDobVIEW FOR EACH ROW

BEGIN

DELETE FROM EMPLOYEE WHERE EmployeeID = :OLD.EmployeeID;

END;

DELETE FROM EmpDobVIEW WHERE EmployeeID =25;


Lab Record 8
(Functions and Procedures)

1. write a procedure that is passed a student’s


identification number and returns back the student’s full
name and phone number from the student table to the
calling program. also write an anonymous block with the
procedure call.

Create or Replace Procedure stud(StudID IN NUMBER, LName OUT


VARCHAR2,FName VARCHAR2, Phone OUT NUMBER) IS
BEGIN
SELECT LAST, FIRST, PHONE INTO LName, FName, Phone from
Student Where StudentID = StudID;
EXCEPTION
When OTHERS Then
DBMS_OUTPUT.PUT_LINE(INTO ||' Not existed');
END stud;

DECLARE
StudentID NUMBER;
LName STUDENT.LAST%TYPE;
FName STUDENT.FIRST%TYPE;
Phone STUDENT.PHONE%TYPE;
BEGIN
StudentID:= & StudentID;
PROC_STUD(StudentID, LName, FName, Phone);
DBMS_OUTPUT.NEW_LINE;
DBMS_OUTPUT.PUT_LINE(FName||' '||LName||' '||Phone);
END;
2.Write a function and pass a department number to it. if the
table does not contain that department number, return a false
value, otherwise return true. print the appropriate message in
the calling program based on the result.

CREATE OR REPLACE FUNCTION func_dept(DCOUNT NUMBER) RETURN VARCHAR2 IS


PRESENTFLAG VARCHAR2(5);
BEGIN
IF(DCOUNT >=1) THEN
PRESENTFLAG :='TRUE';
ELSE
PRESENTFLAG :='FALSE';
END IF;
RETURN PRESENTFLAG;
END func_dept;

DECLARE
VDEPT DEPT.DEPTID%TYPE;
Counter NUMBER(2);
flag VARCHAR2(5);
BEGIN
dept_id :=&dept_id;
SELECT count(*) INTO Counter FROM DEPT WHERE DeptID = dept_id;
flag:= func_dept (Counter);
IF(flag ='TRUE') THEN
DBMS_OUTPUT.PUT_LINE(flag ||' '|| dept_id ||'Exists');
ELSE
DBMS_OUTPUT.PUT_LINE(flag ||' '|| dept_id ||Not Exists');
END IF;
END;
3. write a package that contains a procedure and a function.
the procedure is passed a room number. if the room number exists,
the procedure gets the capacity of the room and the building name
from the location table. if the room number does not exist, the
procedure performs the appropriate exception-handling routine.
the function is passed a csid and returns maximum number of seats
available in the course section.

Create or Replace Package pack as


procedure room_proc(room_no in location.roomno%type);
function fseat(fcsid crssection.csid%type) return number;
end pack;
create or Replace package BODY pack as
procedure room_proc(room_no in location.roomno%type) is
pcapacity location.capacity%type;
pbuilding location.building%type;
Begin
Select capacity, building into pcapacity,
pbuilding from location where roomno = room_no;
dbms_output.put_line('building name' ||pbuilding
||'capacity'||pcapacity);
exception
When no_data_found then
dbms_output.put_line(room_no||' not exist');
When too_many_rows then
dbms_output.put_line(room_no||' more than one location');
When others then
dbms_output.put_line(' error ');
End room_proc;
Function fseat(fcsid crssection.csid%type) return number is
maxseat number;
Begin
Select maxcount into maxseat from crssection where csid = fcsid;
Exception
When no_data_found then
dbms_output.put_line(fcsid||'does not exist');
Return maxseat;
End fseat;
End pack;

DECLARE
maxseat number;
csid number;
room_no number;
begin
csid := &csid;
maxseat := pack.fseat(csid);
dbms_output.put_line('for course '|| csid||' max seats are
'||maxseat);
room_no :=&room_no;
pack.room_proc(room_no);
END;
Lab Record 9
(Exceptions)

1. Write PL/SQL block to retrieve employees based on


qualification Id. If the qualification Id returns more than
one row, handle the exception with the appropriate handler
and print the message ‘More than one employee with such
qualification’. If qualification Id returns no employee,
handle the exception with the appropriate handler and
display the message ‘No employees with such qualification’.
If the qualification Id returns one employee, then print
that employee’s name, qualification and salary.

SET SERVEROUTPUT ON;


DECLARE
Cursor CSR is SELECT LName, FName, e.QualID, q.QualDesc, Salary
FROM EMPLOYEE e, QUALIFICATION q Where e.QualID=q.QualID;
Counter NUMBER(2); qual_id NUMBER(2);
BEGIN
qual_id:= & qual_id;
Select Count(LName) INTO Counter FROM EMPLOYEE e,
QUALIFICATION q WHERE e.QualID =q.QualID AND e.QualID = qual_id;
IF COUNTER = 1 THEN
FOR I in CSR
LOOP
IF(qual_id =I.QualID) THEN
DBMS_OUTPUT.PUT_LINE (I.LNAME||' '||I.FNAME||'
'||I.QUALDESC||' '||I.SALARY);
END IF;
END LOOP;
ELSIF COUNTER = 0 THEN Raise NO_DATA_FOUND;
ELSIF COUNTER > 1 THEN RAISE many_rows;
END IF;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE(‘No employees with such qualification’);
WHEN many_rows THEN
DBMS_OUTPUT.PUT_LINE(‘More than employee with such qualification
END;

2. Write PL/SQL block that retrieves entire COURSE table into a


cursor. Then, ask user to input a courseId to search. If
course exists then print its information, but if not throw a
user-defined exception and handle it with a message ‘Course
does not exist’.

SET SERVEROUTPUT ON;


DECLARE
cid COURSE.courseid%TYPE;
not_existed Exception;
Cursor CSR is Select * FROM COURSE;
counter number(2);
BEGIN
cid := '&cid';
select count(*) into counter from course where courseid=cid;
If counter <> 0 then
FOR i IN CSR
LOOP
IF (cid = i.courseid) THEN
DBMS_OUTPUT.PUT_LINE(i.courseid||'
'||i.title||' '||i.credits||' '||i.prereq);
END IF;
END LOOP;
Else raise not_existed;
End If;
EXCEPTION
WHEN not_existed THEN
DBMS_OUTPUT.PUT_LINE('Course does not exist');
END;

3. Write PL/SQL block that asks user to input first number,


second number and an arithmetic operator (+, -, *, or /). If
operator is invalid, throw and handle a userdefined exception.
If second number is 0 and the operator is /, handle ZERO_DIVIDE
predefined server exception.

SET SERVEROUTPUT ON;


DECLARE
Invailed_operation EXCEPTION;
Num_one number(5); Num_two number(5); operation varchar(5);
BEGIN
Num_one:= &cone;
Num_two:= &ctwo;
operation:= '&coper';
IF (coper<>'+' AND coper<>'-' AND coper<>'*' AND coper<>'/') THEN
raise Invailed_operation;
ELSIF ((coper = '/') AND (ctwo = 0)) THEN
raise ZERO_DIVIDE;
ELSIF (coper = '+') THEN
DBMS_OUTPUT.PUT_LINE(cone + ctwo);
ELSIF (coper = '-') THEN
DBMS_OUTPUT.PUT_LINE(cone - ctwo);
ELSIF (coper = '*') THEN
DBMS_OUTPUT.PUT_LINE(cone * ctwo);
ELSIF (coper = '/') THEN
DBMS_OUTPUT.PUT_LINE(cone / ctwo);
END IF;
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE(‘Error dividing on Zero’);
WHEN INVALID_OPER THEN
DBMS_OUTPUT.PUT_LINE(‘Invailed_operation');
END;

Вам также может понравиться