2015-10-02 99 views
0

我創建觸發器來更新其他表進行審計。 我正在審計的主表是「僱用」,審計表是「salary_history」。每一次更新都是在Emplyed表中進行的,薪水錶必須更新。 我這個觸發器在Oracle 11g中的工作:problema在oracle中創建觸發器來更新其他表

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 

的problema是,當我運行此觸發我收到此錯誤:

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。

我應該做些什麼修改?

回答

0
  • Oracle具有行級和語句級觸發器。只有行級觸發器才能訪問:new:old僞存儲器。您的觸發器當前被定義爲語句級觸發器。您需要添加FOR EACH ROW以使其成爲行級觸發器。
  • insert聲明中獲取max(id)+1是一個非常糟糕的主意。除非您有單個用戶應用程序,否則會導致多個會話獲得相同的值並導致重複鍵錯誤。創建一個序列並使用該序列。
  • 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