Oracle 11g:游标内部过程中的游标。我必须关闭打开的游标吗?

时间:2013-01-30 10:42:34

标签: oracle plsql oracle11g cursor

在Oracle 11g中,PL / SQL上下文完成功能/程序时会自动关闭打开的游标。为什么在Web用户的许多示例中打开和关闭游标?

这是向后兼容吗?

REF-CURSOR怎么样?离开程序还关闭他们吗?

如果光标应该关闭,那么处理异常会怎么样?在EXCEPTION块中,我是否必须检查所有游标ISOPEN然后关闭它们?

基本脚本演示了自动关闭功能:

DECLARE
  PROCEDURE TEST IS
    CURSOR CUR_CLIENTS IS SELECT DUMMY CL_ID FROM DUAL;
    TYPE RT_CLIENTS IS TABLE OF CUR_CLIENTS%ROWTYPE;
    LT_CLIENTS RT_CLIENTS;
  BEGIN
    IF CUR_CLIENTS%ISOPEN THEN
      DBMS_OUTPUT.PUT_LINE('CLOSING CURSOR');
      CLOSE CUR_CLIENTS;
    END IF;
    OPEN CUR_CLIENTS;
    LOOP
      FETCH CUR_CLIENTS BULK COLLECT INTO LT_CLIENTS LIMIT 1000;
      EXIT WHEN LT_CLIENTS.COUNT = 0;
      FOR I IN 1..LT_CLIENTS.COUNT LOOP
        DBMS_OUTPUT.PUT_LINE(LT_CLIENTS(I).CL_ID);
      END LOOP;
    END LOOP;
  END TEST;
BEGIN
  DBMS_OUTPUT.PUT_LINE('--------------------');
  TEST;
  DBMS_OUTPUT.PUT_LINE('--------------------');
  TEST;
  DBMS_OUTPUT.PUT_LINE('--------------------');
  TEST;
  DBMS_OUTPUT.PUT_LINE('--------------------');
END;

1 个答案:

答案 0 :(得分:1)

在你的脚本中,你做错了,因为你正在检查光标是否打开,如果光标已经打开则关闭它,然后再次重新打开。如果光标已经打开,那么不要关闭它,只需使用它。

在plsql中,     内部区域内打开的游标显然没有被隐式关闭。如果它们被关闭,我就不会超过打开游标的最大数量。


根据我的经验:

SQL> DECLARE    
  2     CURSOR last99 IS SELECT * FROM dual;    
  3  BEGIN
  4    DECLARE    
  5       CURSOR test01 IS SELECT * FROM dual;
  6       CURSOR test02 IS SELECT * FROM dual;    
  7       CURSOR test03 IS SELECT * FROM dual;    
............................    
............................    
 51       CURSOR test47 IS SELECT * FROM dual;    
 52       CURSOR test48 IS SELECT * FROM dual;    
 53    BEGIN    
 54       OPEN test01;    
 55       OPEN test02;    
 56       OPEN test03;   

 ..............    
...............   

 99       OPEN test46;    
100       OPEN test47;  
101       OPEN test48;    
102    END;    
104    --This last OPEN will cause an error     
105    --from too many cursors.    
106    OPEN last99;    
107  END;    
108  /    
DECLARE    
*    
ERROR at line 1:    
ORA-01000: maximum open cursors exceeded    
ORA-06512: at line 2    
ORA-06512: at line 106 

您也可以在例外块中关闭光标。