ORACLE for LOOP with Cursor

时间:2013-07-27 14:14:42

标签: oracle for-loop cursor fetch

我有使用Cursor和fetch的LOOP语句,但是我可以“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;

我想要:

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;
/

由于FETCH Cur_emp INTO emp_rec INVALID CURSOR ORA-01001

,这不起作用

1 个答案:

答案 0 :(得分:1)

删除FETCHEXIT WHEN,并将emp_rec引用替换为item,如下所示:

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;
/