What it means
A cursor must be open before you FETCH from it or CLOSE it. If it is not, Db2 does not run the statement and returns -501 with SQLSTATE 24501.
The cursor may have been open earlier. A ROLLBACK closes it, and so does a COMMIT unless the cursor was declared WITH HOLD. Some errors close open cursors as well, including -911, -913, -904, -901, -802 and a few others. An error while evaluating a predicate can also close it.
Typical causes
- A COMMIT inside the fetch loop on a cursor declared without WITH HOLD.
- A ROLLBACK, or a deadlock or timeout (-911), that closed the cursor.
- An earlier SQL error the program did not check, followed by another FETCH.
- Program logic that skips the OPEN or runs CLOSE twice.
- The OPEN failed, but the program carried on to FETCH.
How to fix it
- Look at the SQLCODE of the statements just before the -501. That error is the real problem.
- Check whether the program commits inside the loop. If so, declare the cursor WITH HOLD or reopen and reposition after each commit.
- Test SQLCODE after every OPEN and FETCH and stop the loop on any negative value.
- Trace the paragraph flow to confirm OPEN runs before the first FETCH and CLOSE runs once.