Oracle 异常处理
在编程语言中异常处理是必不可少的部分,plsql 也不例外,一个良好的提示能让调试和排查中少走很多弯路,简单记录一下oracle 异常处理中常用的部分:
- pragma 用来定义异常标识符(系统已经定义了大部分异常标识符,即常量)
语法:
declare
e_20001; - 初始化异常变量
pragma exception_init(e_20001,-20001); --对异常变脸e_20001 进行初始化
- 引发异常 (触发异常后,异常代码会进入异常处理程序)
raise
e_20001; - 异常处理部分
exception
when e_20001 then
raise_application_error(-20001,'错误说明部分')
when others then
raise_application_error(-20002,'其他错误说明'||sqlerrm);
- 步骤
1. e_20001 exception ; //定义异常变量
2. pragma exception_init(e_20001,-20001);//初始化异常变量
3. raise e_20001;//抛出异常
4. exception //处理异常
when e_20001 then
statement_0;
when others then
other_statement;
示例:
1.创建触发器(在emp员工信息表上)
create or replace trigger tr_insert_emp
before insert on emp for each row
declare
e_20001 exception; --异常标识符
e_20003 exception; --重复插入
rcount integer;
pragma exception_init(e_20001,-20001);
begin
select count(1) into rcount from dept where deptno=:new.deptno;
if rcount<1 then
raise e_20001;
end if;
select count(1) into rcount from emp where empno=:new.empno or
(ename=:new.ename and deptno=:new.deptno);
if rcount>0 then
raise e_20003;
end if;
exception
when e_20001 then
raise_application_error(-20001,'该部门不存在,不能插入没有部门的员工信息!');
when e_20003 then
raise_application_error(-20003,'该员工已存在,不能重复插入!');
when others then
raise_application_error(-20002,'插入员工失败!');
end;
2.插入数据
insert into emp(empno,ename,job,mgr,hiredate,sal,comm,deptno)
values(1003,'测试1','程序员',6700,to_date('1996-05-01','yyyy-mm-dd'),1280,200,40);
- 效果
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!