ORA-01403 - 未找到数据 - 即使游标SELECT语句运行正常

时间:2016-01-07 06:35:43

标签: sql oracle plsql

declare
CURSOR C1 IS
    Select to_date(DateRange,'dd-mm-rrrr') DateRange 
    from (select to_date('01-JAN-2016','DD-MON-RRRR') - 1 + level as DateRange
      from    DUAL
      where   (TO_DATE('01-JAN-2016', 'DD-MON-RRRR') - 1 + level) <= LAST_DAY(TO_DATE('31-DEC-2016', 'DD-MON-RRRR'))
      connect by level<=366)
where substr(to_char(DateRange,'DAY'),1,3) in ('SUN','SAT');
begin
   if not c1%ISopen
      then
      open C1;
end if;
  dbms_output.put_line("Cursor is created and number of affected rows are: " || c1%rowcount);
  close c1;
end;
/

即使创建游标中使用的select语句运行正常,但是当我尝试执行代码时,它会抛出错误 - ORA-01403 - 找不到数据

2 个答案:

答案 0 :(得分:2)

您打开光标,但不要获取它。 来自文档:

  

%ROWCOUNT属性可以附加到的光标属性   游标或游标变量的名称。打开游标时   %ROWCOUNT归零。在第一次获取之前,cursor_name%ROWCOUNT   返回0.此后,它返回到目前为止提取的行数。   如果最新的提取返回一行,则该数字会递增。

代码应该是这样的:

DECLARE
   CURSOR C1
   IS
      SELECT TO_DATE (DateRange, 'dd-mm-rrrr') DateRange
        FROM (    SELECT TO_DATE ('01-JAN-2016', 'DD-MON-RRRR') - 1 + LEVEL
                            AS DateRange
                    FROM DUAL
                   WHERE (TO_DATE ('01-JAN-2016', 'DD-MON-RRRR') - 1 + LEVEL) <=
                            LAST_DAY (TO_DATE ('31-DEC-2016', 'DD-MON-RRRR'))
              CONNECT BY LEVEL <= 366)
       WHERE SUBSTR (TO_CHAR (DateRange, 'DAY'), 1, 3) IN ('SUN', 'SAT');

   a   DATE;
BEGIN
   IF NOT c1%ISOPEN
   THEN
      OPEN C1;
   END IF;

   LOOP
      FETCH c1 INTO a;

      EXIT WHEN C1%NOTFOUND;
   END LOOP;

   DBMS_OUTPUT.put_line (
      'Cursor is created and number of affected rows are: ' || c1%ROWCOUNT);

   CLOSE c1;
END;
/

答案 1 :(得分:0)

你的选择陈述不对。将to_date替换为to_char

declare
CURSOR C1 IS
    select to_char(DateRange,'dd-mm-rrrr') DateRange   --replaced to_date with to_char
    from 
      (
        select to_date('01-JAN-2016','DD-MON-RRRR') - 1 + level as DateRange
        from    DUAL
        where   (TO_DATE('01-JAN-2016', 'DD-MON-RRRR') - 1 + level) <= LAST_DAY(TO_DATE('31-DEC-2016', 'DD-MON-RRRR'))
        connect by level<=366
      )
    where substr(to_char(DateRange,'DAY'),1,3) in ('SUN','SAT');
begin
   if not c1%ISopen
      then
      open C1;
end if;
  dbms_output.put_line("Cursor is created and number of affected rows are: " || c1%rowcount);
  close c1;
end;
/

从内部查询返回date,但在主select子句中,您在to_date上使用date,这可能就是您无法获得所需结果的原因。