Oracle数据库—异常处理

oracle异常处理
在pl/sql语句书写时,需要处理的异常
— 不做异常处理时
declare
v_name emp.ename%type;
v_sal emp.sal%type;
begin
select ename,sal
into v_name,v_sal
from emp
where empno = &no;
if v_sal <3000 then
dbms_output.put_line(v_name||’的工资是:’||v_sal);
end if;
end;
在不做异常处理的时候,在输入员工编号的值的时候,如果在数据库中没有,就会报错

select * from emp;
–7369(empno) <3000(sal)
–7839 (empno) >3000

–oracle的异常处理
declare
v_name emp.ename%type;
v_sal emp.sal%type;
begin
select ename,sal
into v_name,v_sal
from emp
where empno = &no;
if v_sal <3000 then
dbms_output.put_line(v_name||’的工资是:’||v_sal);
end if;
exception
when no_data_found then
dbms_output.put_line(‘员工号输入错误!’);
when others then
dbms_output.put_line(‘其他错误!’);
end;

–预定义异常处理
declare
v_name emp.ename%type;
v_sal emp.sal%type:=&salary;
begin
select ename into v_name from emp where sal = v_sal;
dbms_output.put_line(v_name||’的工资是:’||v_sal);
exception
when no_data_found then
dbms_output.put_line(‘没有该工资的员工’);
when too_many_rows then
dbms_output.put_line(‘多个员工具有该工资’);
when others then
dbms_output.put_line(‘其他异常’);
end;

select * from emp;
–800(sal), 一个员工
–1250 多个员工
–8000 0个员工

–获取异常的错误代码和错误信息
begin
delete from dept where deptno = &deptno;
exception
when others then
dbms_output.put_line(sqlcode||’####’||sqlerrm);
end;

–非预定义异常的处理
declare
–1:定义非预定义异常的标识符
e_fk exception;
–2:将定义好的异常与oracle错误建立关联
— -2292错误代码
pragma exception_init(e_fk,-2292);
begin
delete from dept where deptno = &deptno;
exception
–3:捕获并处理异常
when e_fk then
dbms_output.put_line(‘此部门下有员工,不能删除此部门!’);
when others then
dbms_output.put_line(sqlcode||’####’||sqlerrm);
end;

–自定义异常
declare
v_empno emp.empno%type:=&empno;
–1:定义异常
e_no_result exception;
begin
update emp set sal = sal + 100 where empno = v_empno;
if sql%notfound then
–2:指定触发异常的时机
raise e_no_result;
else
commit;
end if;
exception
–3:捕捉并处理异常
when e_no_result then
dbms_output.put_line(‘数据更新失败!’);
when others then
dbms_output.put_line(‘其他错误’);
end;

–异常处理函数sqlcode和sqlerrm的使用
declare
v_empno emp.empno%type:= &empno;
v_ename emp.ename%type:= ‘&ename’;
v_deptno emp.deptno%type:= &deptno;
begin
insert into emp(empno,ename,deptno)values(v_empno,v_ename,v_deptno);
if sql%found then
dbms_output.put_line(‘数据插入成功!’);
commit;
end if;
exception
when others then
dbms_output.put_line(‘错误号:’||sqlcode);
dbms_output.put_line(‘错误信息:’||sqlerrm);
end;

 

(0)
上一篇 2022年3月22日
下一篇 2022年3月22日

相关推荐