The following procedure is followed in most of the situations in PL/SQL:
- Open a cursor
- Start a loop
- Fetch the cursor
- Check whether rows are returned
- Process
- Close the loop
- Close the cursor
Cursor FOR loop allows us to simplify this procedure by letting PL/SQL do most of the things for us.
Let us rewrite the previous example (used in Cursors with Parameters) again using Cursor FOR loop
Using a cursor FOR loop
DECLARECURSOR cur1_dept IS SELECT deptno, dname
FROM dept ORDER BY deptno;
CURSOR cur1_emp (par1_dept VARCHAR2) IS
SELECT ename, salary
FROM emp
WHERE deptno = par1_dept
ORDER BY ename;
var_total_salary NUMBER (10,2);
BEGIN
FOR r1_dept IN cur1_dept LOOP
DBMS_OUTPUT.PUT_LINE ('Department : ' || r1_dept.deptno|| ' - '|| r1_dept.dname);
var_total_salary := 0;
FOR r1_emp IN cur1_emp (r1_dept.deptno) LOOP
DBMS_OUTPUT.PUT_LINE ('Name: ' ||r1_emp.ename || 'Salary:'||r1_emp.salary);
var_total_salary := var_total_salary + r1_emp.salary;
END LOOP;
DBMS_OUTPUT.PUT_LINE ('Total Salary for Dept: ' || var_total_salary);
END LOOP;
END;
/