MainframeKit

-501

SQLSTATE 24501NEGATIVE SQLCODE

The program ran FETCH or CLOSE on a cursor that is not open. Often a COMMIT or an earlier SQL error closed it without the program noticing.

MOST LIKELY

A COMMIT inside the fetch loop on a cursor declared without WITH HOLD.

FIRST CHECK

Look at the SQLCODE of the statements just before the -501. That error is the real problem.

TRY IT ▸

MainframeKit assistant

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

  1. Look at the SQLCODE of the statements just before the -501. That error is the real problem.
  2. Check whether the program commits inside the loop. If so, declare the cursor WITH HOLD or reopen and reposition after each commit.
  3. Test SQLCODE after every OPEN and FETCH and stop the loop on any negative value.
  4. Trace the paragraph flow to confirm OPEN runs before the first FETCH and CLOSE runs once.