需要Trigger中的列名,旧值和新值

时间:2015-04-20 06:56:10

标签: oracle plsql triggers oracle11g

我们的要求是如果表中的任何1个列名都在更新,我们需要在另一个表中插入列名,所以我写了这段代码

CREATE OR REPLACE TRIGGER Test AFTER
  UPDATE ON XX_table
   FOR EACH Row 
   BEGIN FOR C IN
    (SELECT column_name
    FROM User_Tab_Columns
    WHERE Upper(Table_Name) = 'XX_table_name'    ORDER BY column_id ASC) 
    LOOP 
    IF Updating (c.column_name) 
    THEN
    INSERT INTO Xx_Trigger_table    (Rt_Id ,Updated_Column ,updated_status) VALUES(:Old.Rt_Id,C.Column_Name,'Y');
    END IF;
END LOOP;
END;

现在客户需要旧值以及XX_Trigger_Table中的新值。我不能写

INSERT INTO Xx_Trigger_table    (Rt_Id ,Updated_Column ,updated_status,old_value, new_value) VALUES(:Old.Rt_Id,C.Column_Name,'Y',:old.c.column_name,:new.c.column_name);

请建议我在表格中插入新旧值。 在此先感谢。

1 个答案:

答案 0 :(得分:0)

如果您遵循这种方法,就像@Alex Poole建议您必须包含您要记录的所有列。请参阅此程序及其输出。

CREATE OR REPLACE TRIGGER Test1 AFTER
  UPDATE ON TESTEMP
   FOR EACH Row 
   BEGIN FOR C IN
    (SELECT column_name
    FROM User_Tab_Columns
    WHERE Upper(Table_Name) = 'TESTEMP'    ORDER BY column_id ASC) 
    LOOP 
    IF Updating (c.column_name)  then
    IF (c.column_name='EMPNO') then
    INSERT INTO test_audit    (col_name,old_val,new_val,upd_stat) VALUES (C.column_name,:Old.empno,:New.empno,'Y');
    ELSIF
    (c.column_name='ENAME') then
    INSERT INTO test_audit    (col_name,old_val,new_val,upd_stat) VALUES (C.column_name,:Old.ENAME,:New.ENAME,'Y');
    ELSIF
    (c.column_name='MGR') then
    INSERT INTO test_audit    (col_name,old_val,new_val,upd_stat) VALUES (C.column_name,:Old.MGR,:New.MGR,'Y');
    END IF;
    END IF;
END LOOP;
END;



SQL> select * from testemp;

     EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------- ----------
      7369 SMITH      CLERK           7902 17-DEC-80        800                    20
      7499 ALLEN      SALESMAN        7698 20-FEB-81       1600        300         30
      7521 WARD       SALESMAN        7698 22-FEB-81       1250        500         30
      7566 JONES      MANAGER         7839 02-APR-81       2975                    20


SQL> select * from test_audit;

no rows selected

SQL> update testemp set empno=6677 , ename='JUPITER' where empno=1234;

1 row updated.

SQL> COMMIT;

Commit complete.

SQL> select * from test_audit;

COL_NAME   OLD_VAL    NEW_VAL    U
---------- ---------- ---------- -
EMPNO      1234       6677       Y
ENAME      SMITH      JUPITER    Y