ORA-01002: 提取顺序不正确

ORA-01002: fetch out of sequence

我在 oracle 数据库中创建了一个过程,该过程 return 在引用游标中包含数据,我希望它 return 该游标的行数也作为输出变量。经过测试,P_count 变量被正确填充,但是当我试图打开游标时,出现了 'ORA-01002: fetch out of sequence' 错误。我以前读过它,我发现问题是因为我在代码中使用了 fetch 语句。但是直到现在我还没有发现如何解决它。感谢您的帮助,谢谢。以下是我的程序:

PROCEDURE IS_CLIENT_LOGGED_IN (
  P_CLIENT_NUM  Varchar2,
  P_CURSOR out  SYS_REFCURSOR ,
  P_COUNT OUT   NUMBER,
  P_ERROR out   Varchar2
) AS
  cur_rec Varchar2(1024);
BEGIN
   BEGIN 
     Open P_CURSOR FOR
       SELECT ID
         FROM tbl_registration
        WHERE tbl_client_id = P_CLIENT_NUM  
          AND tbl_logout_date is null;

     LOOP
      FETCH P_CURSOR INTO cur_rec;  
      EXIT WHEN P_CURSOR%notfound;
      P_COUNT := P_CURSOR%rowcount;--will return row number beginning with 1
     END LOOP;
   EXCEPTION WHEN OTHERS THEN 
     P_ERROR := 'Unable to select Data from tbl_registration' ||SQLERRM;
   END;    
END IS_CLIENT_LOGGED_IN;

根据您的意见,程序应该是这样的:

PROCEDURE IS_CLIENT_LOGGED_IN (
  P_CLIENT_NUM  Varchar2,
  P_CURSOR out  SYS_REFCURSOR ,
  P_COUNT OUT   NUMBER,
  P_ERROR out   Varchar2
) AS
  cur_rec Varchar2(1024);
BEGIN
     Open P_CURSOR FOR
       SELECT ID
         FROM tbl_registration
        WHERE tbl_client_id = P_CLIENT_NUM  
          AND tbl_logout_date is null;

     LOOP
      FETCH P_CURSOR INTO cur_rec;  
      EXIT WHEN P_CURSOR%notfound;
      P_COUNT := P_CURSOR%rowcount;--will return row number beginning with 1
     END LOOP;
     CLOSE P_CURSOR;

     Open P_CURSOR FOR
       SELECT ID
         FROM tbl_registration
        WHERE tbl_client_id = P_CLIENT_NUM  
          AND tbl_logout_date is null;

   EXCEPTION WHEN OTHERS THEN 
     P_ERROR := 'Unable to select Data from tbl_registration' ||SQLERRM;
END IS_CLIENT_LOGGED_IN;

效率不高,但这正是您所要求的。 无论如何,我看不出有任何理由逐一递增 P_COUNT

制作

SELECT COUNT(*) INTO P_COUNT
     FROM tbl_registration
    WHERE tbl_client_id = P_CLIENT_NUM  
      AND tbl_logout_date is null;

Open P_CURSOR FOR
   SELECT ID
     FROM tbl_registration
    WHERE tbl_client_id = P_CLIENT_NUM  
      AND tbl_logout_date is null;

得到相同的。