Cursor and exception assignment
Below are two sets PL/SQL that produce the same output, the output is shown at the bottom
of this assignment.
First problem:
Explain the code in the first example (line by line).
Explain the code in the second example (overview). Be sure to comment on the open/close of
cursors and draw appropriate conclusions about the FOR in this situation.
DECLARE
v_driveno donation.driveno%TYPE;
v_drive_name drive.drivename%TYPE;
CURSOR drive_cursor IS
SELECT driveno FROM donation
ORDER BY driveno;
CURSOR drive_name_cursor IS
SELECT drivename FROM drive
WHERE v_driveno = driveno;
BEGIN
OPEN drive_cursor;
LOOP
FETCH drive_cursor INTO v_driveno;
EXIT WHEN drive_cursor%NOTFOUND;
IF drive_name_cursor%ISOPEN THEN
CLOSE drive_name_cursor;
END IF;
OPEN drive_name_cursor;
LOOP
FETCH drive_name_cursor INTO v_drive_name;
EXIT WHEN drive_name_cursor%NOTFOUND;
INSERT into drive_info
VALUES(v_driveno, v_drive_name);
END LOOP;
CLOSE drive_name_cursor;
END LOOP;
CLOSE drive_cursor;
END;
/
DECLARE
v_driveno donation.driveno%TYPE;
v_drive_name drive.drivename%TYPE;
v_NameFlag BOOLEAN;
CURSOR drive_cursor IS
SELECT driveno FROM donation
ORDER BY driveno;
CURSOR drive_name_cursor IS
SELECT drivename FROM drive
WHERE v_driveno = driveno;
BEGIN
v_driveno := ' ';
FOR v_DriveIDData IN drive_cursor LOOP
IF v_driveno != v_DriveIDData.driveno THEN
v_driveno := v_DriveIDData.driveno;
v_NameFlag := FALSE;
OPEN drive_name_cursor;
FETCH drive_name_cursor INTO v_drive_name;
IF drive_name_cursor%FOUND THEN
v_NameFlag := TRUE;
END IF;
CLOSE drive_name_cursor;
END IF;
IF v_NameFlag = TRUE THEN
INSERT into drive_info
VALUES(v_driveno, v_drive_name);
END IF;
END LOOP;
END;
/
SQL> select * from drive_info;
DRI DRIVE_NAME
--- ---------------
100 Kids Shelter
100 Kids Shelter
100 Kids Shelter
100 Kids Shelter
200 Animal Home
200 Animal Home
300 Health Aid
300 Health Aid
8 rows selected.
Second problem:
Design, develop, and run your own program using a single cursor.
Third problem:Using your COPIES of the employee and department tables provided by
Oracle or using similiar tables that provide employee, salary, job and dept in one table
and dept number and department name in another table write the following program.
Use the dept table to step through sequentially and bring up the records with the same
department from the employee file. Using an IF calculate a new salary based on the job.
Update each record on the employee file with the new salary. In addition calculate
the total salary for each department and create a new table with the department number, the
department name and the salary.
Fourth problem:
Write an anonymous block of code that will catch an Oracle defined error. Be sure to
include WHEN OTHERS THEN in your code.
Fifth problem:
Write an anonymous block of code that will catch a user defined logic error.