Task-7 DBMS LAB
Task-7 DBMS LAB
7. Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops
using ERROR Handling, BUILT –IN Exceptions, USE defined Exceptions, RAISE-
APPLICATION ERROR.
PL/SQL program demonstrating WHILE loops, numeric FOR loops, nested loops, error
handling, built-in exceptions, user-defined exceptions, and the use of
RAISE_APPLICATION_ERROR.
Scenario
The program processes a list of students and their marks. It:
1. Loops through a list of students using a FOR loop.
2. Calculates and prints a running total of marks using a WHILE loop.
3. Demonstrates nested loops to check for duplicate StudentID.
4. Implements error handling:
o Built-in exceptions: Handle division by zero.
o User-defined exceptions: Raise an error if a student's marks are invalid (e.g.,
negative or above 100).
o RAISE_APPLICATION_ERROR: Provide a meaningful error message.
Step 1: Create Table and Insert Data
Create the Students Table:
Sql>CREATE TABLE Students (
StudentID INT PRIMARY KEY,
Name VARCHAR(100) NOT NULL,
Marks INT CHECK (Marks BETWEEN 0 AND 100)
);
Insert Sample Data:
Sql>INSERT INTO Students VALUES (1, 'Alice', 85);
Sql>INSERT INTO Students VALUES (2, 'Bob', 72);
Sql>INSERT INTO Students VALUES (3, 'Charlie', 48);
Sql>INSERT INTO Students VALUES (4, 'Diana', 64);
Sql>INSERT INTO Students VALUES (5, 'Eve', 101);
Step 2: PL/SQL Program
DECLARE
-- Cursor to fetch students
CURSOR StudentCursor IS
SELECT StudentID, Name, Marks
FROM Students;
-- User-defined exception
InvalidMarks EXCEPTION;
BEGIN
-- FOR loop to iterate through all students
FOR StudentRecord IN StudentCursor LOOP
v_StudentID := StudentRecord.StudentID;
v_Name := StudentRecord.Name;
v_Marks := StudentRecord.Marks;
EXCEPTION
-- Handle user-defined exception
WHEN InvalidMarks THEN
DBMS_OUTPUT.PUT_LINE('Error: Invalid marks detected. Please check the data.');