oracle变异表触发器中ora-04091错误原因及解决方案
变异表是指激发触发器的dml语句所操作的表
当对一个表创建行级触发器时,有下列两条限制:
1.不能读取或修改任何触发语句的变异表;
2.不能读取或修改触发表的一个约束表的primary key,unique 或foreign key关键字的列, 但可以修改其他列
例如:有这样一个需求:在更新员工所在部门或向部门插入新员工时,部门中员工人数不超过7人
如果按照下面的触发器写就会使update操作时报错
create or replace trigger updatetrigger
before update on emp
for each row
declare
v_num number;
begin
select count(*) into v_num from emp
where deptno = :new.deptno;
if (v_num > 7) then
raise_application_error(-20001,
'员工数多于'||v_num);
end if;
end updatetrigger;
ora-04091: 表 scott.emp 发生了变化, 触发器/函数不能读它
ora-06512: 在 scott.updatetrigger, line 4
ora-04088: 触发器 'scott.updatetrigger' 执行过程中出错
如果既想更新变异表,同时又需要查询变异表,那么如何处理呢?
将行级触发器与语句级触发器结合起来,,在行级触发器中获取要修改的记录的信息,存放到一个软件包的全局变量中,然后在语句级后触发器中利用软件包中全局变量信息对变异表的查询,并根据查询的结果进行业务处理
例如:
为了实现在更新员工所在部门或向部门插入新员工时,部门中员工人数不超过7人,可以在emp表上创建两个触发器,同时创建一个共享信息的包
create or replace package mutate_pkg
as
v_deptno number(2);
end;
create or replace trigger rmutate_trigger
before insert or update of deptno on emp
for each row
begin
mutate_pkg.v_deptno:=:new.deptno;
end;
create or replace trigger smutate_trigger
after insert or update of deptno on emp
declare
v_num number(3);
begin
select count(*) into v_num from emp
where deptno = mutate_pkg.v_deptno;
if v_num>7 then
raise_application_error(-20003,'这部门的员工太多了 '||
mutate_pkg.v_deptno);
end if;
end;
这样操作,就不会报ora-04091: 表scott.emp 发生了变化,触发器/函数不能读它错误了。
相关阅读:
oracle触发器的使用
oracle触发器给表自身的字段重新赋值出现ora-04091异常
oracle创建触发器调用含参数存储过程
oracle触发器查询统计本表
