PLSQL"错误游标已经打开"

时间:2015-08-19 20:06:32

标签: oracle for-loop plsql 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;

但我一直收到错误消息

原因:尝试打开已打开的光标。

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

我不知道发生了什么。当我更改代码以取消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;

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

2 个答案:

答案 0 :(得分:6)

您正在打开光标:

open cur;

然后不关闭它,在光标循环中再次打开:

for rec in cur loop

“for cursor loop”构造首先打开光标。无需事先打开它。请参阅documentation

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

答案 1 :(得分:3)

使用Cursor的两种方式:

  1. OPEN; FETCH INTO; CLOSE;
  2. FOR I IN C1;
  3. 方法1: OPEN C1; LOOP; FETCH C1 INTO; END LOOP; CLOSE C1;

    DECLARE
    v_code_id   your_users.cod_id%type;  
    v_code_user your_users.cod_user%type ;
    cursor C_users is select cod_id,cod_user from your_users where 1=1; 
    BEGIN
    OPEN C_users;  --opening cursor
    loop
    Fetch C_users into v_code_id,v_code_user; -- Fetching from Cursoe
    exit when C_users%NOTFOUND;
    DELETE from your_users WHERE cod_emp  IN (v_code_id);
    dbms_output.put_line( 'USER : ' || ' ' ||  v_code_user || ' is deleted.' );
    End Loop;
    commit;
    Close C_users ; --Closing Cursor
    END;
    

    <强>输出:

    USER :  mahi is deleted.
    USER :  xyz is deleted.
    
    Statement processed.
    

    方法2: FOR i in C1; LOOP; END LOOP

    DECLARE
    cursor C_users is
     select cod_id,cod_user from your_users where 1=1; 
    BEGIN
    For rec in C_users 
    loop
     DELETE from your_users WHERE cod_emp  IN (rec.cod_id );
     dbms_output.put_line( 'USER : ' || ' ' ||  rec.cod_user || ' is deleted.' );
    End Loop;
    commit;
    END;
    

    <强>输出:

    USER :  xyz is deleted.
    USER :  mahi is deleted.