2015-08-19 94 views
1

我有以下代碼:PLSQL「錯誤遊標已打開」

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循環時,它是否告訴我光標已經打開?

回答

6

您正在打開的遊標:

open cur; 

,然後不關閉它,你在遊標循環再次打開:

了「遊標循環」結構先打開遊標。無需事先打開它。見documentation:使用Cursor

「 FOR循環語句後面的光標隱式聲明其循環指數爲指定光標返回行類型的記錄變量,然後打開一個遊標」

3

兩種方式:

  1. OPEN; FETCH INTO; CLOSE;
  2. FOR I IN C1;

方法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; 

OUTPUT:

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; 

OUTPUT:

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