Compound Trigger
官方文档见:
http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/triggers.htm#LNPLS694
下面给出一个例子
CREATE TABLE log (
emp_id NUMBER(6),
l_name VARCHAR2(25)
);
-- Create trigger that updates log and then reads employees
CREATE OR REPLACE TRIGGER log_deletions
AFTER DELETE ON emp FOR EACHROW
DECLARE
n INTEGER;
BEGIN
INSERT INTO log (emp_id,l_name) VALUES (
:OLD.empno,
:OLD.ename
);
SELECT COUNT(*) INTO n FROMemp;
DBMS_OUTPUT.PUT_LINE('Thereare now ' || n || ' employees.');
END;
DELETE FROM emp WHERE empno = 7935;
SQL Error: ORA-04091: table SCOTT.EMP is mutating, trigger/functionmay not see it
ORA-06512: at "SCOTT.LOG_DELETIONS", line 9
ORA-04088: error during execution of trigger 'SCOTT.LOG_DELETIONS'
04091. 00000 - "table%s.%s is mutating, trigger/function may not see it"
*Cause: A trigger (or auser defined plsql function that is referenced in
this statement)attempted to look at (or modify) a table that was
in the middle ofbeing modified by the statement which fired it.
*Action: Rewrite the trigger(or function) so it does not read that table.
很明显,该Trigger试图读取正在被更改的表,因而触发了ORA-04091。
我们可以用Oacle 11g的新特性compound Trigger重写这个Trigger,从而解决问题。
CREATE OR REPLACE TRIGGER log_deletions
FOR DELETE ON emp
COMPOUND TRIGGER
n int;
AFTER EACH ROW IS
BEGIN
INSERT INTO log (emp_id,l_name) VALUES (
:OLD.empno,
:OLD.ename
);
END AFTER EACH ROW;
AFTER STATEMENT IS
BEGIN
SELECT COUNT(*) INTO n FROMemp;
DBMS_OUTPUT.PUT_LINE('Thereare now ' || n || ' employees.');
END AFTER STATEMENT;
END;
DELETE FROM emp WHERE empno = 7935;
1 rows deleted.
请注意:读取emp的select语句被放入AfterStatement段中,表示这条语句将在整个SQL Statement完成后才被执行。这就规避了ORA-04091错误。
更多Oracle相关信息见Oracle 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=12
