0
SQL - Cursor if no records not working

CREATE OR REPLACE procedure verify_data
IS
cursor c1 is 
select 
  e.name 
from 
  table3 e 
where 
  id IN (select id from table1)
  and id in (select id from table2);
BEGIN
if c1%notfound then
DBMS_OUTPUT.PUT_LINE('no records found');
end if;

FOR eData in c1
   LOOP

      DBMS_OUTPUT.PUT_LINE(eData.name);
   END LOOP;

END;
/

如果有记录,我的结果将被输出。但是如果没有找到记录,则不会显示任何内容。如果选择语句中没有记录,是否有任何异常处理或我可以做的事情来使我的输出“未找到记录”显示出来。

更新:

我添加后

结束循环

EXCEPTION
WHEN NO_DATA_FOUND THEN 
DBMS_OUTPUT.PUT_LINE('no records found');

在 END 之前;

SQL> 执行验证数据();

PL/SQL 过程成功完成。

也不显示。。

4

4 回答 4

0

结束前;添加以下代码 WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE('no records found');

于 2012-11-26T05:31:32.170 回答
0

您无法在游标/循环中处理 NO_DATA_FOUND

试试下面的例子

CREATE OR REPLACE PROCEDURE verify_data
IS
CURSOR c1 is 
SELECT 
  e.name 
FROM 
  table3 e 
WHERE 
  id IN (SELECT ID FROM table1)
  AND id in (SELECT ID FROM table2);

eData   table3.name%TYPE ; 

no_data EXCEPTION ;
BEGIN
OPEN c1 ;
LOOP
FETCH c1 INTO eData;

IF c1%NOTFOUND THEN
  RAISE no_data ;
ELSE
 DBMS_OUTPUT.PUT_LINE(eData);
 EXIT ;
END IF;
END LOOP ;
CLOSE c1;
EXCEPTION 
WHEN no_data THEN
    DBMS_OUTPUT.PUT_LINE('*** Exc: no data');

END;
于 2012-11-26T10:48:28.920 回答
0

试试这个代码:

CREATE OR REPLACE procedure verify_data
IS
no_result exception;
cursor c1 is 
select 
e.name 
from 
table3 e 
where 
id IN (select id from table1)
and id in (select id from table2);
BEGIN
FOR eData in c1
LOOP
  DBMS_OUTPUT.PUT_LINE(eData.name);
  if c1%notfound then
   raise no_result;
  end if;
END LOOP;
EXCEPTION
WHEN no_result THEN 
DBMS_OUTPUT.PUT_LINE('no records found');
END; 
/
于 2012-11-26T10:18:27.043 回答
0

Please check below procedure

  CREATE OR REPLACE procedure verify_data
    IS
    cursor c1 is 
    select 
      e.name 
    from 
      table3 e 
    where 
      id IN (select id from table1)
      and id in (select id from table2);
    BEGIN
    loop
    FETCH c1 INTO eData;
    EXIT WHEN c1%NOTFOUND;
    DBMS_OUTPUT.PUT_LINE(eData.name);
    end loop;
    exception 
    when no_data_found then
        dbms_output.put_line('*** Exc: no data');

    END;
    /
于 2012-11-26T10:01:36.420 回答