Question

I've been reading up on database cursors, and every bit of sample code I've seen explicitly opens and closes the cursor. I've only used them a few times and I've never had to do this. Can anyone tell me why it is necessary to do this? I know if you don't close a cursor you can create memory leakes but i've never had to open one.

Thanks

Was it helpful?

Solution

If your cursors are global(I guess you used local cursors where this is not a problem, because they are closed when they get out of scope) you must explicitly close them.

There are several problems about not closing global cursors

  • The memory used for the cursor is not deallocated
  • There is a maximum number of cursors you can have opened. Eventually you would not be able to create another one, because you will have the maximum number of cursors opened.

If you are asking why do I have to use cursors? - Sometimes you need to loop through the rows (like using a regular for loop). You can not do that in the set oriented approach - you have to use cursors.

OTHER TIPS

you only have to open and close explicit cursors. Implicit cursors have the advantage of being managed automatically by Oracle. Example of implicit cursors:

DECLARE
   l_dept dept%rowtype;
BEGIN
   -- implicit SELECT INTO
   SELECT * INTO l_dept FROM dept WHERE deptno = :deptno;
   -- implicit LOOP
   FOR cc IN (SELECT emp.* FROM emp WHERE deptno = l_dept.deptno) LOOP
      dbms_output.put_line('emp='||cc.empno);
   END LOOP;
END;
/

Implicit cursors are more concise in the code, you don't have to worry about closing them. I also find it clearer to have the code of the cursor where it is actually used. I seldom use explicit cursor, and only if they can be reused in many places in a package (then why not put it in a single proc?).

This is quite a good practice, as you can easily get the SQL status of any particular query (ROWCOUNT, NOTFOUND etc), whether or not you have run other queries in the meantime. Also, you can reuse your cursors within a package, create data types of their ROWTYPE, make loops over them, and all kinds of good stuff!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top