从插入后触发器触发的存储过程引发的变异表错误

时间:2014-12-07 07:22:09

标签: oracle plsql database-trigger mutating-table

我需要在插入'之后通过'来调用存储过程。每当数据插入表时触发但我遇到错误ORA-04091:表TEST.EMP正在变异,触发器/函数可能看不到它"。我理解这个错误背后的原因,但是如何通过复合触发器克服这个问题而不会干扰程序呢?

create TABLE emp(
id NUMBER(4),
emp_name VARCHAR2(30),
dept_name VARCHAR2(10));

create or replace PROCEDURE emp_count(dept_name_v emp.dept_name%TYPE) as
DECLARE
dept_emp_count NUMBER(4) := 0;
BEGIN
SELECT count(*) INTO dept_emp_count FROM emp WHERE dept_name = dept_name_v;
UPDATE dept_stat SET d_emp_count = dept_emp_count WHERE dept_name =  dept_name_v;
END;

create or replace TRIGGER dept
AFTER INSERT ON emp
FOR EACH ROW
BEGIN
emp_count(:NEW.dept_name);
END;

1 个答案:

答案 0 :(得分:1)

文档中有一个示例如何创建复合触发器:
http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/triggers.htm#CHDFEBFJ

只需在此示例中更改一些标识符和声明,您将获得针对您的案例的触发器:

CREATE OR REPLACE TRIGGER some_trigger
 FOR INSERT ON  emp
COMPOUND TRIGGER

TYPE dept_names_t IS TABLE OF emp.dept_name%TYPE INDEX BY SIMPLE_INTEGER;
  dept_names  dept_names_t;
  idx       SIMPLE_INTEGER := 0;

 -- AFTER EACH ROW Section:

  AFTER EACH ROW IS
  BEGIN
    idx := idx + 1;
    dept_names(idx) := :NEW.dept_name;
  END AFTER EACH ROW;

AFTER STATEMENT IS
  BEGIN
   FOR  j IN 1..idx
   LOOP
     emp_count(dept_names(j));
   END LOOP;
END AFTER STATEMENT;
END; 
/