Oracle系列之异常处理

涉及到表的处理请参看原表结构与数据  Oracle建表插数据等等

使用select into语句读取tb_Employee的一行,使用异常处理处理no_data_found和two_many_rows的系统预定义异常

set serveroutput on;
declare
emp tb_Employee%rowtype;
begin
select * into emp from tb_Employee 
where ename = 'SCOTT';
dbms_output.put_line('SCOTT ''s sal is : ' || emp.sal); 
exception
when no_data_found then
dbms_output.put_line('no data found exception');
end;
/
 
declare
emp tb_Employee%rowtype;
begin
select * into emp from tb_Employee 
where deptno =20;
dbms_output.put_line('The sal is : ' || emp.sal); 
exception
when too_many_rows then
dbms_output.put_line('too many rows exception');
end;
/

使用嵌套异常端处理,循环读取emp_id_minval 和 emp_id_maxval之间的员工,使得其中存在不存在员工号。输出对应员工的ename,不存在的员工输出“not exists such empolyee”。

declare
emp_id tb_Employee.pk_Employee_ID%type;
v_ename tb_Employee.ename%type;
emp_id_minval tb_Employee.pk_Employee_ID%type;
emp_id_maxval tb_Employee.pk_Employee_ID%type;
begin
emp_id_minval:=&emp_id_minval;
emp_id_maxval:=&emp_id_maxval;
for emp_id in emp_id_minval..emp_id_maxval loop
begin
select ename into v_ename from tb_Employee
where pk_Employee_ID=emp_id;
dbms_output.put_line('ename:'||v_ename);
exception
when no_data_found then
dbms_output.put_line('not exists such empolyee');
end;
end loop;
end;
/

写一个处理ora-01400 (不能插入空值)的系统异常的示例程序和异常处理

declare
insert_excep exception;
pragma exception_init(insert_excep, -01400);
begin
insert into tb_Department
(pk_Department_ID, dname) values (50, null);
exception
when insert_excep then
dbms_output.put_line('INSERT OPERATION FAILED');
dbms_output.put_line(SQLERRM);
end;
/

使用SQLCODE,SQLERRM,获得异常的编号和错误信息,并输出异常的编号和错误信息

declare
emp tb_Employee % rowtype;
error_code number;
error_message varchar2(255);
begin
select * into emp from tb_Employee 
where ename = 'SCOTT';
dbms_output.put_line('SCOTT ''s salary is : ' || emp.sal); 
exception
when too_many_rows then
error_code := SQLCODE;
error_message := SQLERRM;
dbms_output.put_line(error_code || ' ' || error_message);
end;
/

自定义一个异常,抛出这个异常并处理

declare
invalid_department exception;
name varchar2(20) := '&name';
deptno number := &deptno;
begin
update tb_Department
set dname = name
where pk_Department_ID = deptno;
if sql % notfound then
raise invalid_department;
end if;
exception
when invalid_department then
dbms_output.put_line('No such department');
end;
/

使用raise_application_error抛出一个应用异常

declare
v_ename tb_Employee.ename%type:='&v_ename';
e_name exception;
pragma exception_init(e_name, -20999);
begin
delete from tb_Employee
where ename = v_ename;
if sql % notfound then
raise_application_error(-20999, 'This is not a valid ename');
end if;
exception
when e_name then
dbms_output.put_line('The ename '||v_ename||' exists, Please choose again');
end;  
/
原文地址:https://www.cnblogs.com/tufujie/p/5075956.html