为什么游标总是已打开?

时间:2014-12-16 04:02:27

标签: sql oracle oracle11g cursor

我想获取版本大于输入且属于同一版本组的所有消息。所以我创建了一个游标来遍历messageHeader表并使用游标获取所有行。但我得到一个游标已经打开异常。我在这做错了什么。我打开并关闭了循环外的光标。

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;

2 个答案:

答案 0 :(得分:1)

尝试此代码可能对您有所帮助: -

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
  FOR mHeader in mHeaderCurs loop exit when mHeaderCurs%notfound; 
      --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;
     --SELECT VALID_FROM INTO gasDay FROM message_header where ID = scheduleID;
  end ALLOW_SCHEDCALC;/

答案 1 :(得分:1)

在光标上使用FOR循环时,例如FOR mHeader in mHeaderCurs,Oracle PL / SQL引擎为您打开/关闭游标。

根本不需要打开或关闭光标。

P.S。这个代码首先没有意义,因为这是在程序的开始,所以根据定义,游标不能打开:

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