PL/SQL异常处理

PL/SQL异常处理

系统异常

由数据库管理系统捕获处理 预定义异常:有异常编码,异常名称,异常信息
no_data-found :没有找到数据
too_many_rows :返回多条数据

declare
	v_name varchar2(10);
begin
	select ename into v_name from test_emp where empno=1234;
		dbms_output.put_line(v_name);
exception
	when no_data_found then
		dbms_output.put_line('no data');
	when too_many_rows then
		dbms_output.put_line('too many rows');
	when others then
		dbms_output.put_line('error');
end;
非预定义异常

有编码,有信息,没有异常名称

declare
	e_child exception;
	pragma exception_init(e_child,-02292);
begin
	delete from dept where deptno=10;
		dbms_output.put_line('deleted');
	exception
		when e_child then
			dbms_output.put_line('has constraint');
		when others then
			dbms_output.put_line('others');
end;

自定义异常

由程序员捕获并处理的错误信息

declare
	v_id binary_integer := &no;
	v_comm test_emp.comm%type;
	--定义异常名称
	e_null exception;
	--将异常名称跟异常编码绑定
	pragma exception_init(e_null,-20101);
begin
	select comm into v_comm from test_emp where empno=v_id;
		dbms_output.put_line(v_comm);
	if v_comm is null then
	--抛出异常
		raise e_null;
	else
		update test_emp set comm=comm+100 where empno=v_id;
 	end if;
	exception
	--捕获异常
	when e_null then
		dbms_output.put_line('comm is null');
	--捕获其他类型的异常
	when others then
		dbms_output.put_line('others');
end;
--------示例 2--------
declare
	v_id binary_integer := &no;
	v_comm test_emp.comm%type;
	e_null exception;
	pragma exception_init(e_null,-20101);
begin
	select comm into v_comm from test_emp where empno=v_id;
		dbms_output.put_line(v_comm);
	if v_comm is null then
		raise e_null;
	else
		update test_emp set comm=comm+100 where empno=v_id;
		commit;
	end if;
	exception
	when others then 
	--打印输出异常编码 sqlcode 和异常信息
	sqlerrm dbms_output.put_line(sqlcode||'---'||sqlerrm);
end;

如果在循环中出现异常信息会中断代码块的继续执行,如果需要抛出异常以后继续执行代码块需要使用如下结构:
EXCEPTION
when others then
null;

在 for …LOOP ENDLOOP 循环中捕捉异常,必须用 begin end 包起来,否则会
报错

declare
	V_SQL VARCHAR2(255);
	errorCode number; --异常编码
	errorMsg varchar2(1000); --异常信息
	out_return varchar2(1000);
	flag varchar2(10);
CURSOR TP IS
	SELECT TABLE_NAME,CONSTRAINT_NAME FROM USER_CONSTRAINTS WHERE CONSTRAINT_TYPE = 'P';
BEGIN
	FOR E IN TP LOOP
BEGIN
	V_SQL := 'ALTER TABLE ' || E.TABLE_NAME || ' ' || 'DISABLE' ||' '||  'CONSTRAINT ' || E.CONSTRAINT_NAME;
	
DBMS_OUTPUT.PUT_LINE(V_SQL);

EXECUTE IMMEDIATE (V_SQL);
---- 异常捕获
EXCEPTION
	when others then
		errorCode := SQLCODE;
		errorMsg := SUBSTR(SQLERRM, 1, 200);
		flag := 'false'; 
		out_return := 'flag=' || flag || ',errorCode='||errorCode || ',errorMsg=' || errorMsg;
			dbms_output.put_line(out_return);
			null;
		END;
	END LOOP;
end;

更多相关知识,请关注我哦,或者猛戳头像,谢谢!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值