`

PL/SQL程序设计-学习笔记4--异常

 
阅读更多
五、异常错误处理
有三种类型的异常错误:预定义(Predefined)错误、非预定义(Predefined)错误、用户定义(User_define)错误。
例1:预定义的异常处理
declare
v_empno employees.employee_id%type := &v_empno;
v_sal employees.salary%type;
begin
select salary into v_sal from employees where employee_id = v_empno for update;
if v_sal<3000 then
update employees set salary = salary + 3000 where employee_id = v_empno;
dbms_output.put_line('编码为'||v_empno||'员工工资已更新');
else
dbms_output.put_line('编码为'||v_empno||'员工工资不需要更新');
end if;
exception
when no_data_found then
dbms_output.put_line('数据库中没有编码为'||v_empno||'的员工');
when too_many_rows then
dbms_output.put_line('程序运行错误,请使用游标');
when others then
dbms_output.put_line('其他错误');
end;
例2:非预定义的异常处理
declare
v_depno dept.deptno%type := &v_depno;
deptno_remaining exception;
-- -2292 是违反一致性约束的错误代码
pragma exception_init(deptno_remaining,-2292);
begin
delete from dept where deptn = v_depno;
exception
when deptno_remaining then
dbms_output.put_line('违反数据完整性约束');
when others then
dbms_output.put_line(sqlcode||'--'||sqlerrm);
end;
例3:用户自定义的异常处理
declare
v_empid employees.employee_id%type := &v_empid;
no_result exception;
begin
update employees set salary = salary + 100 where employee_id = v_empid;
if sql%notfound then
raise no_result;
end if;
exception
when no_result then
dbms_output.put_line('数据更新失败');
when others then
dbms_output.put_line('出现其他异常');
end;
SQLCODE 返回错误代码数字
SQLERRM 返回错误信息
如:sqlcode=-100 --> sqlerrm='no_data_found'
例4:将ORACLE错误代码及其信息存入错误代码表
create table errors(errnum number(4),errmsg varchar2(100));

declare
err_msg varchar2(100);
begin
/* 得到所有ORACLE错误信息 */
for err_num in -100..0 loop
err_msg:=sqlerrm(err_num);
insert into errors values(err_num,err_msg);
end loop;
end;

drop table errors;
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics