Search code examples
oraclefor-loopcursorfetch

ORACLE FOOR LOOP with Cursor


I have LOOP statement with Cursor and fetch and that works but I wanna "FOR LOOP".

DECLARE
   emp_rec employees%ROWTYPE;
   CURSOR Cur_emp IS 
     SELECT * 
       FROM employees 
      order by employees.last_name asc; 
BEGIN
   OPEN Cur_emp;
   LOOP
      FETCH Cur_emp INTO emp_rec; 
      exit when Cur_emp%notfound;
      dbms_output.put_line(‘Employee Name–>’|| emp_rec.LAST_NAME);
   END LOOP;
   CLOSE Cur_emp;  
END;

I wanna like:

DECLARE
   emp_rec employees%ROWTYPE;
   CURSOR Cur_emp IS 
     SELECT * 
       FROM employees 
      order by employees.last_name asc; 
BEGIN
   FOR item IN Cur_emp
   LOOP
     FETCH Cur_emp INTO emp_rec;
     exit when Cur_emp%notfound;
     dbms_output.put_line(‘Employee Name–>’|| emp_rec.LAST_NAME);
   END LOOP;
END;
/

This does not works because of FETCH Cur_emp INTO emp_rec INVALID CURSOR ORA-01001


Solution

  • Remove the FETCH and EXIT WHEN, and replace emp_rec reference with item, like this:

    DECLARE
    CURSOR Cur_emp IS SELECT * FROM employees order by employees.last_name asc; 
    BEGIN
    FOR item IN Cur_emp
    LOOP
    dbms_output.put_line(‘Employee Name–>’|| item.LAST_NAME);
    END LOOP;
    END;
    /