PLSQL"错误游标已经打开"

use*_*249 1 oracle plsql for-loop cursor

我有以下代码:

DECLARE 
  f_cd fee.fee_cd%type;
  f_name fee.fee_nm%type; 
  f_new_cd fee.new_fee_cd%type;
  f_new_name fee.new_fee_nm%type;

  Cursor cur is
    SELECT Fee_cd, fee_nm, new_fee_cd, new_fee_nm FROM Fee;
BEGIN
  if cur%ISOPEN then
    close cur;
  end if;

  open cur;

  for rec in cur loop
    fetch cur INTO f_cd, f_name, f_new_cd, f_new_name;
    dbms_output.put_line ('The Fee Code ' || f_cd
                          || ' is the one you selected and it''s name is '
                          || f_name);
  end loop;

  close cur;
END;
Run Code Online (Sandbox Code Playgroud)

但我一直收到错误信息

原因: 尝试打开已打开的游标.

操作: 在重新打开之前先关闭光标.

我不知道发生了什么.当我改变代码以取消它for loop并使用loop... end loop它所使用的结构时.功能代码如下:

loop
  fetch cur INTO f_cd, f_name, f_new_cd, f_new_name;
  dbms_output.put_line ('The Fee Code ' || f_cd
                        || ' is the one you selected and it''s name is '
                        || f_name);    
  exit when cur%notfound;
end loop;

close cur;
END;
Run Code Online (Sandbox Code Playgroud)

为什么当我使用for循环时它告诉我光标已经打开?

Old*_*mer 6

你正在打开光标:

open cur;
Run Code Online (Sandbox Code Playgroud)

然后在不关闭它的情况下,再次在游标循环中打开:

for rec in cur loop
Run Code Online (Sandbox Code Playgroud)

"for cursor loop"构造首先打开游标.无需事先打开它.查看文档:

"游标FOR LOOP语句隐式声明其循环索引为指定游标返回的行类型的记录变量,然后打开游标."