是否必须关闭 PLSQL 块中的游标
Is it mandatory to close cursor in PLSQL block
请看下面的流程。我没有关闭光标,它工作正常。我在这里错过了什么吗?
是强制关闭游标还是Oracle自动关闭?
CREATE OR REPLACE PROCEDURE pr_cursor_test IS
CURSOR emp_cur IS SELECT empno, ename FROM emp;
emprec emp_cur%rowtype;
BEGIN
OPEN emp_cur;
LOOP
FETCH emp_cur INTO emprec;
EXIT WHEN
emp_cur%notfound;
--Do Something
dbms_output.put_line(emprec.ename);
END LOOP;
END;
This article on Oracle website 说得很清楚了。
When you declare a cursor in a package (that is, not inside a
subprogram of the package) and the cursor is opened, it will stay open
until you explicitly close it or your session is terminated.
When the cursor is declared in a declaration section (and not in a
package), Oracle Database will also automatically close it when the
block in which it is declared terminates. It is still, however, a good
idea to explicitly close the cursor yourself. If the cursor is moved
to a package, you will have the now necessary CLOSE already in place.
And if it is local, then including a CLOSE statement will also show
other developers and your manager that you are paying attention.
在您的代码示例中,CURSOR 被声明为过程的一部分(而不是程序包的一部分),这意味着,当过程执行完成时,游标会自动关闭。但是,如果您在代码中有 OPEN cursor
语句,则最好使用 CLOSE cursor
语句进行编码。它使代码在未来易于理解和支持。
请看下面的流程。我没有关闭光标,它工作正常。我在这里错过了什么吗? 是强制关闭游标还是Oracle自动关闭?
CREATE OR REPLACE PROCEDURE pr_cursor_test IS
CURSOR emp_cur IS SELECT empno, ename FROM emp;
emprec emp_cur%rowtype;
BEGIN
OPEN emp_cur;
LOOP
FETCH emp_cur INTO emprec;
EXIT WHEN
emp_cur%notfound;
--Do Something
dbms_output.put_line(emprec.ename);
END LOOP;
END;
This article on Oracle website 说得很清楚了。
When you declare a cursor in a package (that is, not inside a subprogram of the package) and the cursor is opened, it will stay open until you explicitly close it or your session is terminated.
When the cursor is declared in a declaration section (and not in a package), Oracle Database will also automatically close it when the block in which it is declared terminates. It is still, however, a good idea to explicitly close the cursor yourself. If the cursor is moved to a package, you will have the now necessary CLOSE already in place. And if it is local, then including a CLOSE statement will also show other developers and your manager that you are paying attention.
在您的代码示例中,CURSOR 被声明为过程的一部分(而不是程序包的一部分),这意味着,当过程执行完成时,游标会自动关闭。但是,如果您在代码中有 OPEN cursor
语句,则最好使用 CLOSE cursor
语句进行编码。它使代码在未来易于理解和支持。