Wednesday, July 16, 2008

Solve ORA-01002: Fetch Out Of Sequence Error Message Oracle Dialect

This is an error that is generated specifically by Oracle. It can happen under a variety of circumstances, but lets look at what the Oracle database documentation says:

ORA-01002: fetch out of sequence

Cause: This error means that a fetch has been attempted from a cursor which is no longer valid. Note that a PL/SQL cursor loop implicitly does fetches, and thus may also cause this error. There are a number of possible causes for this error, including: 1) Fetching from a cursor after the last row has been retrieved and the ORA-1403 error returned. 2) If the cursor has been opened with the FOR UPDATE clause, fetching after a COMMIT has been issued will return the error. 3) Rebinding any placeholders in the SQL statement, then issuing a fetch before reexecuting the statement.

Action: 1) Do not issue a fetch statement after the last row has been retrieved - there are no more rows to fetch. 2) Do not issue a COMMIT inside a fetch loop for a cursor that has been opened FOR UPDATE. 3) Reexecute the statement after rebinding, then attempt to fetch again.

This can all be confusing. And it can be frustrating.

Sometimes, I've seen this simply due to data in the database problems. If it's troubling you, do a small query on your Oracle8i or 9 database and see if you are searching past the last record in the returned list. If you are, you might just be missing data or something in your database - phantom rows!

"After enabling Hibernate log and DB trace, we noticed 2 records missing in the DB, and it seems that this caused the problem. So, for now, I would say that the problem isn't related to hibernate." Forum Posting

I've also seen this caused by people looping through a ref cursor that is being used as an out parameter in the code. Instead, you can avoid the ORA-01002: Fetch Out Of Sequence Exception by opening two different and separate database cursors, and use one as the out parameter, and use the other cursor throughout the loop.

No comments: