空游标和异常

时间:2018-07-12 12:02:35

标签: oracle exception plsql cursor

我试图获取异常只是为了查看其工作方式。我声明一个游标,该游标未从表中获取任何数据,因为根据我的where子句,薪水不超过60000。游标应该为空?我尝试了两种方法来获取错误消息,但是却收到诸如“匿名块已完成”之类的消息。

set serverout ON
declare
c_empid kt_test.empid%type;

cursor c_kt is select empid into c_empid from kt_test where salary > 60000;

BEGIN
  open c_kt;

  fetch c_kt into c_empid;
exception
WHEN NO_DATA_FOUND THEN
  raise_application_error(-20001,'Data not found for employee');
  close c_kt;
   WHEN OTHERS THEN
    RAISE_APPLICATION_ERROR(-20002,'Other error-'||SQLCODE||'-'||SQLERRM);
end;

set serverout ON
declare
c_empid kt_test.empid%type;

cursor c_kt is select empid into c_empid from kt_test where salary > 60000;

BEGIN
  open c_kt;

  fetch c_kt into c_empid;
  IF c_kt%NOTFOUND THEN 
        DBMS_OUTPUT.PUT_LINE('Explicit Cursor: No data found');
    END IF;
END;

line 1: SQLPLUS Command Skipped: set serverout ON
anonymous block completed

这里缺少什么,这样我会收到错误消息?

3 个答案:

答案 0 :(得分:0)

您可以尝试此变体(略作修改):

set serveroutput ON
declare
  c_empid kt_test.empid%type;

  cursor c_kt is 
  select empid
  from kt_test 
  where salary > 60000;

BEGIN
  open c_kt;
  fetch c_kt into c_empid;
  close c_kt;

  IF c_empid is null THEN 
    DBMS_OUTPUT.PUT_LINE('Explicit Cursor: No data found');
  END IF;
END;

在pl / sql Developer中的匿名块中运行时,输出:“显式光标:未找到数据”

如果需要,第一个代码段将起作用,您需要这样重写它:

declare
  c_empid number;

BEGIN

  select empid 
  into c_empid
  from kt_test
  where salary > 60000;  

exception
  when no_data_found then
    DBMS_OUTPUT.PUT_LINE('Insert into: No data found');
END;

答案 1 :(得分:0)

一个简单的工作示例:

SQL> set serveroutput on
SQL> declare
  2      cursor c is select 1 from dual where 1 = 0;
  3      vN  number;
  4  begin
  5      open c;
  6      fetch c into vN;
  7
  8      if c%NOTFOUND then
  9          dbms_output.put_line('No data');
 10      end if;
 11  end;
 12  /
No data

PL/SQL procedure successfully completed.

SQL>

答案 2 :(得分:0)

或者使用您自己定义的错误消息。

SET serveroutput ON
DECLARE
  custom_err EXCEPTION;
  PRAGMA EXCEPTION_INIT( custom_err, -20001 );
  CURSOR c
  IS
    SELECT 1 FROM dual WHERE 1 = 0;
  vN NUMBER;
BEGIN
  OPEN c;
  FETCH c INTO vN;
  IF c%NOTFOUND THEN
    raise_application_error( -20001, 'This is a custom error' );
  END IF;
EXCEPTION
WHEN custom_err THEN
  dbms_output.put_line( sqlerrm );
END;