Oracle PL/SQL学习之基础篇(2)--例外

时间:2024-08-25 16:04:14

1、例外分类:系统例外、自定义例外

(1)系统例外,参见相关API文档

(2)自定义例外

定义自己的例外:就像自定义变量一样,类型为exception

抛出例外:使用raise抛出自定义例外

set serveroutput on
declare
cursor cemp is select ename from emp where deptno=50; pename emp.ename%type; --self define exception
self_no_data_found exception;
begin
open cemp; fetch cemp into pename;
if cemp%notfound then
--throw self define exception
raise self_no_data_found;
end if;
exception
when self_no_data_found then
dbms_output.put_line('执行了自定义异常!');
if cemp%isopen then
dbms_output.put_line('close cursor!');
close cemp;
end if;
when others then
dbms_output.put_line('执行了others异常!');
if cemp%isopen then
close cemp;
end if;
end;
/

运行结果:

Oracle PL/SQL学习之基础篇(2)--例外

2、我们使用游标,然后尝试抓取游标中的一条记录,并判断是否有值,如果有值,将其赋值给临时变量。如果没有值,触发自定义异常。

create or replace function f_user_qr_groupmemberinfo

(i_phonenumber                   in emp.empno%type, --用户号码

 i_memberphonenumber             in emp.ename%type, --成员号码

 i_result                        out integer        --0:数据库操作异常; 1:查询操作正常 2:没有找到数据

 )

 return MYPACKAGE.empcursor as

  c_groupmemberinfo MYPACKAGE.empcursor; --结果游标

  str_sql_selectsql varchar2(32676) := 'select t.empno '

                                       || 'from emp t '

                                       || 'where t.empno=:i_phonenumber '

                                       ||
'and t.ename=:i_memberphonenumber';
pempno emp.empno%type;
--self define exception
self_no_data_found exception;
temp emp.empno%type;
begin --查询用户主叫号码组内部id open c_groupmemberinfo for str_sql_selectsql
using i_phonenumber, i_memberphonenumber; fetch c_groupmemberinfo into pempno;
if c_groupmemberinfo%notfound then
--throw self define exception
raise self_no_data_found;
end if; temp := pempno; i_result := 1; return c_groupmemberinfo; --异常 exception
when self_no_data_found then
open c_groupmemberinfo for
select 'X' from dual where 1 = 0; i_result := 2; return c_groupmemberinfo;
when others then open c_groupmemberinfo for
select 'X' from dual where 1 = 0; i_result := 0; return c_groupmemberinfo; end f_user_qr_groupmemberinfo;

结果:

Oracle PL/SQL学习之基础篇(2)--例外

自定义的游标:

Oracle PL/SQL学习之基础篇(2)--例外