在oracle中创建触发器以更新其他表的问题

时间:2015-10-02 15:26:01

标签: oracle11g triggers

我创建了一个触发器来更新其他表以进行审核。 我正在接受审计的主要表是“#34;雇用"审计表是" salary_history"。每次更新都在emplyed表中进行,必须更新salary_history。 我在oracle 11g中使用此触发器:

CREATE OR REPLACE TRIGGER salary_auditing
AFTER UPDATE ON employed
REFERENCING NEW AS NEW OLD AS OLD
BEGIN

  INSERT INTO SALARY_HISTORY(ID, EMPLOYED_ID, OLD_SALARY, NEW_SALARY, DATE_MODIFIED) VALUES (SELECT MAX(ID)+1 FROM SALARY_HISTORY, ID, :OLD.salary, :NEW.salary, SYSDATE)

END salary_auditing

问题在于,当我运行此触发器时,我收到此错误:

Relatório de erros -
ORA-04082: referências NEW ou OLD não permitidas nos gatilhos de nível de tabela
04082. 00000 -  "NEW or OLD references not allowed in table level triggers"
*Cause:    The trigger is accessing "new" or "old" values in a table trigger.
*Action:   Remove any new or old references.

在英语中,这意味着表nivel不允许使用NEW或OLD值。

我应该做些什么修改?

1 个答案:

答案 0 :(得分:0)

  • Oracle具有行级和语句级触发器。只有行级触发器才能访问:new:old伪记录。您的触发器当前被定义为语句级触发器。您需要添加FOR EACH ROW才能使其成为行级触发器。
  • max(id)+1语句中获取insert是一个非常糟糕的主意。除非您有一个用户应用程序,否则会导致多个会话获得相同的值并导致重复的键错误。创建序列并使用该序列。
  • REFERENCING NEW AS NEW OLD AS OLD毫无意义。除非您打算为:new:old伪记录提供不同的别名,否则请忽略它。你几乎不应该使用不同的别名。

我希望你想要

create sequence seq_salary_history_id
  start with <<value larger than what is currently in the table>>;

CREATE OR REPLACE TRIGGER salary_auditing
  AFTER UPDATE ON employed
  FOR EACH ROW
BEGIN
  INSERT INTO SALARY_HISTORY(ID, 
                             EMPLOYED_ID, 
                             OLD_SALARY, 
                             NEW_SALARY, 
                             DATE_MODIFIED) 
    VALUES (seq_salary_history_id.nextval, 
            :new.ID, 
            :OLD.salary, 
            :NEW.salary, 
            SYSDATE);
END salary_auditing;

如果您只想在更新salary列时触发触发器(因为这是您跟踪历史记录的唯一内容),请在触发器声明中添加OF salary

CREATE OR REPLACE TRIGGER salary_auditing
  AFTER UPDATE OF salary ON employed
  FOR EACH ROW