G-4330: Always use a CURSOR FOR loop to process the complete cursor results unless you are using bulk operations.
Minor
Maintainability
Reason
It is easier for the reader to see, that the complete data set is processed. Using SQL to define the data to be processed is easier to maintain and typically faster than using conditional processing within the loop.
Since an EXIT
statement is similar to a GOTO
statement,
it should be avoided, whenever possible.
Example (bad)
DECLARE
CURSOR c_employees IS
SELECT employee_id, last_name
FROM employees;
r_employee c_employees%ROWTYPE;
BEGIN
OPEN c_employees;
<<read_employees>>
LOOP
FETCH c_employees INTO r_employee;
EXIT read_employees WHEN c_employees%NOTFOUND;
sys.dbms_output.put_line(r_employee.last_name);
END LOOP read_employees;
CLOSE c_employees;
END;
/
Example (good)
DECLARE
CURSOR c_employees IS
SELECT employee_id, last_name
FROM employees;
BEGIN
<<read_employees>>
FOR r_employee IN c_employees
LOOP
sys.dbms_output.put_line(r_employee.last_name);
END LOOP read_employees;
END;
/