Skip to content

G-3140: Try to use anchored records as targets for your cursors.

Major

Maintainability, Reliability

Reason

Using cursor-anchored records as targets for your cursors results enables the possibility of changing the structure of the cursor without regard to the target structure.

Example (bad)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
declare
   cursor c_employees is
      select employee_id,first_name,last_name
        from employees;
   l_employee_id employees.employee_id%type;
   l_first_name  employees.first_name%type;
   l_last_name   employees.last_name%type;
begin
   open c_employees;
   fetch c_employees into l_employee_id,l_first_name,l_last_name;
   <<process_employees>>
   while c_employees%found
   loop
      -- do something with the data
      fetch c_employees into l_employee_id,l_first_name,l_last_name;
   end loop process_employees;
   close c_employees;
end;
/

Example (good)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
declare
   cursor c_employees is
      select employee_id,first_name,last_name
        from employees;
   r_employee c_employees%rowtype;
begin
   open c_employees;
   fetch c_employees into r_employee;
   <<process_employees>>
   while c_employees%found
   loop
      -- do something with the data
      fetch c_employees into r_employee;
   end loop process_employees;
   close c_employees;
end;
/