0% found this document useful (0 votes)
2 views

Database 5th Lab Notes

The document contains lab notes on PL/SQL programming, detailing the use of cursors, procedures, and functions to manage teacher data, salary updates, course periods, student enrollments, and exam results. It includes examples of SQL queries, exception handling, and the implementation of constraints. Additionally, it provides outputs from executed procedures, demonstrating the successful completion of various tasks.

Uploaded by

Ai Cha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Database 5th Lab Notes

The document contains lab notes on PL/SQL programming, detailing the use of cursors, procedures, and functions to manage teacher data, salary updates, course periods, student enrollments, and exam results. It includes examples of SQL queries, exception handling, and the implementation of constraints. Additionally, it provides outputs from executed procedures, demonstrating the successful completion of various tasks.

Uploaded by

Ai Cha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Database 5th Lab Notes

number of courses taught by each teacher

Procedural Language / SQL , : simply thoses queries integrated in a procedure ,


using procedural logic ( loops , if statements .. )
Treat exception
- Declaration of variables , types , cursors , functions and procedures
- Exception Block : handling excpetions statements
• To handle errors, declare a variable of type EXCEPTION and use it in the
EXCEPTION block.
• The DBMS_OUTPUT.PUT_LINE procedure is used to display output in the console.
• Use the following command in SQL Plus to enable output:
SET SERVEROUTPUT ON
cursor is a pointer to a result of an sql query .

Example :

DECLARE
CURSOR cr IS SELECT LastName FROM TEACHER WHERE Grade =
'Assistant'; -- PL/SQL cursor definition
c_rec cr%rowtype; -- c_rec takes the same type as cr
i BINARY_INTEGER := 0; -- Initialize counter
empty EXCEPTION; -- Exception for empty results
BEGIN
FOR c_rec IN cr LOOP -- Automatically manages the cursor lifecycle
i := i + 1;
DBMS_OUTPUT.PUT_LINE ('Teacher ' || i || ' is ' || c_rec.LastName);
END LOOP;
IF i = 0 THEN RAISE empty; -- Raise exception if no teachers found
ELSE
DBMS_OUTPUT.PUT_LINE ('The grade "Assistant" contains ' || i || '
teacher(s).');
END IF;
EXCEPTION WHEN empty THEN
DBMS_OUTPUT.PUT_LINE ('The grade Assistant does not contain any
Teacher');
END;
/
Functions and Procedures :
PL/SQL code can be saved in a procedure or a function, with or without
parameters.

CREATE [OR REPLACE] PROCEDURE Procedure_name (arg1 type, arg2 type,


...) IS
Declaration of local variables
BEGIN
Statements;
END;

to execute EXECUTE Procedure_name (argument values);


to display the errors SHOW ERRORS PROCEDURE Procedure_name;

DECLARE
-- Define a cursor to fetch teacher data
CURSOR c IS
SELECT TEACHER.TeacherID, TEACHER.FirstName,
TEACHER.LastName, COUNT(COURSE_ASSIGNMENT.CourseID) AS CourseCount
FROM TEACHER
JOIN COURSE_ASSIGNMENT ON TEACHER.TeacherID =
COURSE_ASSIGNMENT.TeacherID
GROUP BY TEACHER.TeacherID, TEACHER.FirstName,
TEACHER.LastName;

BEGIN
-- Iterate over each record in the cursor
FOR rec IN c LOOP
-- Output the teacher details
DBMS_OUTPUT.PUT_LINE('The teacher ' || rec.FirstName || ' '
|| rec.LastName ||
' teaches ' || rec.CourseCount || '
courses.');
END LOOP;
END;
/
OUTPUT :

The teacher Sajida Laichi teaches 2 courses.


The teacher Nesrine Kadouri teaches 5 courses.
The teacher Adem Ghezlane teaches 3 courses.
The teacher Douaa Bennour teaches 3 courses.
The teacher Mohamed Ben Ali teaches 1 courses.
The teacher Hakim Boutaleb teaches 2 courses.
The teacher Anfal Amrane teaches 2 courses.

PL/SQL procedure successfully completed.

2. Add salary constraints and implement


raises
a. Add salary constraint:

From first try it wil display an error indictaing that u can't disable the alredy existing
constraint

ALTER TABLE TEACHER


DISABLE CONSTRAINT CHECK_SALARY ;

ALTER TABLE TEACHER


ADD CONSTRAINT chk_teacher_salary
CHECK (Salary BETWEEN 60000 AND 350000);

b. Procedure to implement salary raises:

CREATE OR REPLACE PROCEDURE UpdateSalary AS


BEGIN

FOR rec IN (SELECT FirstName, LastName, Grade, Salary FROM


TEACHER WHERE Grade = 'Assistant Professor') LOOP
DECLARE
old_salary NUMBER := rec.Salary;
new_salary NUMBER := rec.Salary + rec.Salary * 0.1;
BEGIN
UPDATE TEACHER
SET Salary = new_salary
WHERE FirstName = rec.FirstName AND LastName =
rec.LastName;

DBMS_OUTPUT.PUT_LINE('The salary of the teacher Mr. '


|| rec.FirstName || ' ' || rec.LastName ||
' (' || rec.Grade || ') has
increased from ' || old_salary || ' DA to ' ||
new_salary || ' DA.');
END;
END LOOP;

-- Update salaries and display changes for 'Associate


Professor'
FOR rec IN (SELECT FirstName, LastName, Grade, Salary FROM
TEACHER WHERE Grade = 'Associate Professor') LOOP
DECLARE
old_salary NUMBER := rec.Salary;
new_salary NUMBER := rec.Salary + rec.Salary * 0.2;
BEGIN
UPDATE TEACHER
SET Salary = new_salary
WHERE FirstName = rec.FirstName AND LastName =
rec.LastName;
DBMS_OUTPUT.PUT_LINE('The salary of the teacher Mr. '
|| rec.FirstName || ' ' || rec.LastName ||
' (' || rec.Grade || ') has
increased from ' || old_salary || ' DA to ' ||
new_salary || ' DA.');
END;
END LOOP;
FOR rec IN (SELECT FirstName, LastName, Grade, Salary FROM TEACHER
WHERE Grade = 'Full Professors') LOOP
DECLARE
old_salary NUMBER := rec.Salary;
new_salary NUMBER := rec.Salary + rec.Salary * 0.3;
BEGIN
UPDATE TEACHER
SET Salary = new_salary
WHERE FirstName = rec.FirstName AND LastName =
rec.LastName;

DBMS_OUTPUT.PUT_LINE('The salary of the teacher Mr. '


|| rec.FirstName || ' ' || rec.LastName ||
' (' || rec.Grade || ') has
increased from ' || old_salary || ' DA to ' ||
new_salary || ' DA.');
END;
END LOOP;
END;
/

OUTPUT:

The salary of the teacher Mr. Sajida Laichi (Full Professor) has
increased from
339300 DA to 441090 DA.
The salary of the teacher Mr. Mohamed Ben Ali (Full Professor) has
increased
from 325000 DA to 422500 DA.

PL/SQL procedure successfully completed.

CREATE OR REPLACE PROCEDURE UpdateSalary IS


CURSOR crTeacher IS
SELECT TeacherID, FirstName, LastName, Grade, Salary
FROM Teacher;

cr_rec crTeacher%ROWTYPE;
old_salary NUMBER;
BEGIN
FOR cr_rec IN crTeacher LOOP
old_salary := cr_rec.Salary;

IF cr_rec.Grade = 'Assistant' THEN


cr_rec.Salary := old_salary * 1.10;
ELSIF cr_rec.Grade = 'Associate' THEN
cr_rec.Salary := old_salary * 1.20;
ELSIF cr_rec.Grade = 'Full Professor' THEN
cr_rec.Salary := old_salary * 1.30;
END IF;

DBMS_OUTPUT.PUT_LINE('The salary of ' || cr_rec.FirstName


|| ' ' || cr_rec.LastName ||
' (' || cr_rec.Grade || ') has
increased from ' || old_salary ||
' to ' || cr_rec.Salary);

UPDATE Teacher
SET Salary = cr_rec.Salary
WHERE TeacherID = cr_rec.TeacherID;
END LOOP;
END;
/

3. Procedure to verify course period

CREATE OR REPLACE PROCEDURE Check_Course_Period AS


BEGIN
FOR rec IN (SELECT CourseID, StartDate, EndDate
FROM COURSE_ASSIGNMENT
WHERE EXTRACT(YEAR FROM StartDate) = 2023) LOOP
IF rec.StartDate < rec.EndDate THEN
DBMS_OUTPUT.PUT_LINE('Course ' || rec.CourseID || ':
Valid course Period');
ELSE
DBMS_OUTPUT.PUT_LINE('Course ' || rec.CourseID || ':
Invalid course Period');
END IF;
END LOOP;
END;
/

correcting the procedure:

CREATE OR REPLACE PROCEDURE check_valid_period(p_year NUMBER) IS


CURSOR course_cursor IS
SELECT CourseID, StartDate, EndDate
FROM COURSE_ASSIGNMENT
WHERE EXTRACT(YEAR FROM StartDate) = p_year;

c_rec course_cursor%ROWTYPE;
BEGIN
FOR c_rec IN course_cursor LOOP
IF c_rec.StartDate < c_rec.EndDate THEN
DBMS_OUTPUT.PUT_LINE('Course ' || c_rec.CourseID || ':
Valid Course Period');
ELSE
DBMS_OUTPUT.PUT_LINE('Course ' || c_rec.CourseID || ':
Invalid Course Period');
END IF;
END LOOP;
END;
/

Alternative Solution :

CRAETE OR REPLACE PROCEDURE checkPeriod (CourseID NUMBER)


IS
Cursor cr IS SELECT StartDate , EndDate FROM
Course_Assignment
WHERE CourseID = Courseid;
c_rec cr%rowtype ;

4. Function to return the number of courses a


student is enrolled in

CREATE OR REPLACE FUNCTION Number_of_courses(Student_number NUMBER)


RETURN NUMBER IS
Number_of_courses NUMBER;
Student_name VARCHAR2(100);
BEGIN
SELECT FirstName || ' ' || LastName INTO Student_name
FROM Student
WHERE StudentID = Student_number;

Number_of_courses := 0;

SELECT COUNT(CourseID) INTO Number_of_courses


FROM Enrollment
WHERE StudentID = Student_number;

DBMS_OUTPUT.PUT_LINE('The student ' || Student_name || ' is


enrolled in ' || Number_of_courses || ' courses.');

RETURN Number_of_courses;
END Number_of_courses;
/

Testing the function:

DECLARE
Course_Number NUMBER;
BEGIN
Course_Number := Number_of_courses(1);
END;
/

5. Procedure to add an exam result

CREATE OR REPLACE PROCEDURE Add_Exam_Result(


p_ResultID IN EXAM_RESULT.ResultID%TYPE,
p_StudentID IN STUDENT.StudentID%TYPE,
p_ExamID IN EXAM.ExamID%TYPE,
p_Score IN EXAM_RESULT.Score%TYPE
) AS
v_StudentExist NUMBER;
v_ExamExist NUMBER;
BEGIN
-- Check if ResultID is unique
FOR rec IN (SELECT ResultID FROM EXAM_RESULT WHERE ResultID =
p_ResultID) LOOP
RAISE_APPLICATION_ERROR(-20001, 'Error: ResultID must be
unique.');
END LOOP;
-- Check if StudentID exists
SELECT COUNT(*) INTO v_StudentExist
FROM STUDENT
WHERE StudentID = p_StudentID;

IF v_StudentExist = 0 THEN
RAISE_APPLICATION_ERROR(-20002, 'Error: StudentID does not
exist.');
END IF;

-- Check if ExamID exists


SELECT COUNT(*) INTO v_ExamExist
FROM EXAM
WHERE ExamID = p_ExamID;

IF v_ExamExist = 0 THEN
RAISE_APPLICATION_ERROR(-20003, 'Error: ExamID does not
exist.');
END IF;

-- Insert exam result


INSERT INTO EXAM_RESULT (ResultID, StudentID, ExamID, Score)
VALUES (p_ResultID, p_StudentID, p_ExamID, p_Score);

DBMS_OUTPUT.PUT_LINE('Exam result added successfully.');


EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM);
END;
/

Testing the procedure:

BEGIN
Add_Exam_Result(41, 1, 1, 15); -- Example values
END;
/

You might also like