Search code examples
oracle-databasecursorfetch

Is it mandatory to close cursor in PLSQL block


Please see the below procedure. I did not close cursor and it is working fine. Am I missing something here. Is it mandatory to close cursor or Oracle closes it automatically?

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;

Solution

  • This article on Oracle website is pretty clear about it.

    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.

    In your code example CURSOR is declared as part of procedure (not as part of package), which means, cursor is closed automatically when procedure executioin is complete. However it is best coding practice to CLOSE cursor statement if you have OPEN cursor statement in code. It makes code easy to understand and support in future.