How to Fix ORA-01001: Invalid Cursor in Oracle

Avoid fetching from or closing a cursor that is not open, and see the reworded ORA-01001 message of Oracle AI Database 26ai.

ORA-01001 is raised when code uses a cursor that is not open: a FETCH or CLOSE on a cursor that was never opened or was already closed. In PL/SQL it is the predefined exception INVALID_CURSOR. Oracle AI Database 26ai words the message as "cursor number is invalid or does not exist". The fix is to fetch only between OPEN and CLOSE, and to close only open cursors.

Reproduce the Error

Example:

create table demo_flights (flight_no varchar2(8), status varchar2(10));
insert into demo_flights values ('NA101', 'ON TIME');
commit;
declare
  cursor c_flights is select flight_no from demo_flights;
  v_no demo_flights.flight_no%type;
begin
  open c_flights;
  close c_flights;
  fetch c_flights into v_no;
end;
/
declare
  cursor c_flights is select flight_no from demo_flights;
begin
  close c_flights;
end;
/

Output:

Table DEMO_FLIGHTS created.

1 row inserted.

Commit complete.

declare
*
ERROR at line 1:
ORA-01001: cursor number is invalid or does not exist
ORA-06512: at line 7

declare
*
ERROR at line 1:
ORA-01001: cursor number is invalid or does not exist
ORA-06512: at line 4

The first block fetches after CLOSE; the second closes a cursor it never opened.

Fix: Fetch Between OPEN and CLOSE

Example:

set serveroutput on
declare
  cursor c_flights is select flight_no from demo_flights;
  v_no demo_flights.flight_no%type;
begin
  open c_flights;
  loop
    fetch c_flights into v_no;
    exit when c_flights%notfound;
    dbms_output.put_line(v_no);
  end loop;
  close c_flights;
  -- close only when it is open
  if c_flights%isopen then
    close c_flights;
  end if;
end;
/

Output:

NA101

PL/SQL procedure successfully completed.

The loop fetches until %NOTFOUND, closes once, and a later CLOSE runs only if the cursor is still open.

Things to Know

  • A cursor FOR loop opens, fetches, and closes the cursor itself, which avoids this error.
  • Reading %ROWCOUNT of a closed explicit cursor also raises INVALID_CURSOR.
  • In client programs, ORA-01001 can come from using a statement handle after it was closed, or after a session reconnected.

Related Guides

Conclusion

ORA-01001 means a cursor was used while it was not open. Keep FETCH between OPEN and CLOSE, check %ISOPEN before CLOSE, or let a cursor FOR loop handle the cursor.

Vinish Kapoor
Vinish Kapoor

An Oracle ACE, author of four books on Oracle APEX, SQL and PL/SQL, and Oracle Forms, and a software developer building Oracle database applications since 2001.

guest

0 Comments
Oldest
Newest Most Voted