Database 5th Lab Notes
Database 5th Lab Notes
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.
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 :
From first try it wil display an error indictaing that u can't disable the alredy existing
constraint
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.
cr_rec crTeacher%ROWTYPE;
old_salary NUMBER;
BEGIN
FOR cr_rec IN crTeacher LOOP
old_salary := cr_rec.Salary;
UPDATE Teacher
SET Salary = cr_rec.Salary
WHERE TeacherID = cr_rec.TeacherID;
END LOOP;
END;
/
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 :
Number_of_courses := 0;
RETURN Number_of_courses;
END Number_of_courses;
/
DECLARE
Course_Number NUMBER;
BEGIN
Course_Number := Number_of_courses(1);
END;
/
IF v_StudentExist = 0 THEN
RAISE_APPLICATION_ERROR(-20002, 'Error: StudentID does not
exist.');
END IF;
IF v_ExamExist = 0 THEN
RAISE_APPLICATION_ERROR(-20003, 'Error: ExamID does not
exist.');
END IF;
BEGIN
Add_Exam_Result(41, 1, 1, 15); -- Example values
END;
/