您的位置:首页 > 数据库 > Oracle

ORACLE 不用写NO_DATA_FUND 异常捕获,开发的一个小技巧!

2014-09-30 15:24 246 查看
这是我在工作中发现的一个很实用的小技巧,可以少写一些代码.下面,以scott.emp表为例子

先写一个过程:

create or replace procedure p_get_sal(p_empno int) is

v_sal number;

begin

select a.sal into v_sal from scott.emp a where a.empno = p_empno;

dbms_output.put_line(v_sal);

end;

再调用:

SQL> set serveroutput on

SQL> exec p_get_sal(123456);

begin p_get_sal(123456); end;

ORA-01403: 未找到任何数据

ORA-06512: 在 "SCOTT.P_GET_SAL", line 4

ORA-06512: 在 line 2

如果改写一下:

create or replace procedure p_get_sal(p_empno int) is

v_sal number;

begin

select max(a.sal) into v_sal from scott.emp a where a.empno = p_empno;

dbms_output.put_line(v_sal);

end;

SQL> exec p_get_sal(123456);

PL/SQL procedure successfully completed

则能正确执行.

也就是说,用MAX SUM 等聚合函数,即使在没有找到行的情况下,也会返回一个NULL 行,有了这个NULL行,就不用写NO_DATA_FUND了.在很多时候,需要先去查询一个表,再根据查出来的值做判断,这个时候这样写就很有用,避免了写异常捕获,代码更简洁.



另外,自定义函数找不到值也不会报错:

create or replace function f_get_sal(p_empno int) return number is

v_sal number;

begin

select a.sal into v_sal from scott.emp a where a.empno = p_empno;

return v_sal;

end;

SQL> select f_get_sal(123456) from dual;

F_GET_SAL(123456)

-----------------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: