下面是之后语句级触发器的示例。每当对emp表执行插入、更新或删除操作时,都会向empauditlog表添加一行来记录日期、用户和操作。
CREATE TABLE empauditlog (
audit_date DATE,
audit_user VARCHAR2(20),
audit_desc VARCHAR2(20)
);
CREATE OR REPLACE TRIGGER emp_audit_trig
AFTER INSERT OR UPDATE OR DELETE ON emp
DECLARE
v_action VARCHAR2(20);
BEGIN
IF INSERTING THEN
v_action := 'Added employee(s)';
ELSIF UPDATING THEN
v_action := 'Updated employee(s)';
ELSIF DELETING THEN
v_action := 'Deleted employee(s)';
END IF;
INSERT INTO empauditlog VALUES (SYSDATE, USER,
v_action);
END;
在以下命令序列中,使用两个INSERT命令将两行插入emp表中。这两行的sal和comm列将使用一个UPDATE命令更新。最后,这两行将使用一个DELETE命令同时被删除。
INSERT INTO emp VALUES (9001,'SMITH','ANALYST',7782,SYSDATE,NULL,NULL,10);
INSERT INTO emp VALUES (9002,'JONES','CLERK',7782,SYSDATE,NULL,NULL,10);
UPDATE emp SET sal = 4000.00, comm = 1200.00 WHERE empno IN (9001, 9002);
DELETE FROM emp WHERE empno IN (9001, 9002);
SELECT TO_CHAR(AUDIT_DATE,'DD-MON-YY HH24:MI:SS') AS "AUDIT DATE",
audit_user, audit_desc FROM empauditlog ORDER BY 1 ASC;
AUDIT DATE AUDIT_USER AUDIT_DESC
------------------ -------------------- --------------------
31-MAR-05 14:59:48 SYSTEM Added employee(s)
31-MAR-05 15:00:07 SYSTEM Added employee(s)
31-MAR-05 15:00:19 SYSTEM Updated employee(s)
31-MAR-05 15:00:34 SYSTEM Deleted employee(s)
empauditlog表的内容显示触发了多少次触发器:其中为两次插入分别触发一次,为更新触发一次(即使更改了两行)以及为删除触发一次(即使删除了两行)。