Search code examples
sqloracleoracle11gcursor

Why is always cursor already open?


I want to get all messages who version is greater than the input and belongs to the same version group. So I created a cursor to loop through the messageHeader table and get all the rows using a cursor. But I get a cursor already open exception. What am I doing wrong here. I have opened and closed the cursor outside the loop.

create or replace
PROCEDURE ALLOW_SCHEDCALC (scheduleID IN NUMBER, flag OUT NUMBER)
is
 messageHeaderIDS Number(20,0);
 gasDay timestamp;
 headerCount number(20);
 cursor mHeaderCurs IS SELECT message_header.ID INTO messageHeaderIDS FROM Message_header 
  where version_group_id =(select DISTINCT version_group_id from message_header where ID= scheduleID)
  AND message_header.version > (select DISTINCT version from message_header where ID = scheduleID);
  begin
IF mHeaderCurs %ISOPEN THEN
     CLOSE mHeaderCurs ;
   END IF;
  open mHeaderCurs;
  FOR mHeader in mHeaderCurs
  Loop
    --DBMS_OUTPUT.put_line (mHeader.ID);
    SELECT COUNT(*) into headerCount FROM nomination_process_queue where ID=mHeader.ID;
      IF headerCount > 0
      then
      flag:=0;
     else
      flag:=1;
      end if;
    end loop;
    close mHeaderCurs;
      --SELECT VALID_FROM INTO gasDay FROM message_header where ID = scheduleID;
end ALLOW_SCHEDCALC;

Solution

  • When you use the FOR loop over a cursor, e.g. FOR mHeader in mHeaderCurs, the Oracle PL/SQL engine handles the cursor open/close for you.

    You don't need to open or close the cursor at all.

    P.S. this code never made sense in the first place, since this is at the start of the procedure so by definition the cursor cannot be open:

    begin
    IF mHeaderCurs %ISOPEN THEN
      CLOSE mHeaderCurs ;
    END IF;