我不知道如何创建日志触发器

时间:2018-10-29 15:06:25

标签: oracle plsql database-trigger

我需要为更新之后,插入之后和删除之前创建日志触发器。

accounts_history表中的行数比帐户表中的行多,这让我感到困惑

如何编写触发器?

我尝试这样做,但是没有成功,这就是我创建表和序列的方式。

我是Oracle和plsql的初学者

很抱歉,如果我不能很好地解释我的问题。

create table accounts (
  id number,
  name varchar2(32),
  amount number,
  date date
);

create sequnce acc_seq_id
  start wtih 1
  increment by 1
  nocache
  nocycle;

create table accounts_history (
  id          number
, old_name    varchar2(32)
, new_name    varchar2(32)
, old_amount  number
, new_amount  number
, change_date date
);

我的触发器仅在更新之后

create or replace trigger after_update
after update
on accounts referencing new as new old as old
for each row

begin

iNSERT INTO account_history
(
id, 
name,
old_name,
amount,
old_amount,
date
)
values
(
 :old.id,
 :new.name,
 :old.old_name,
 :new.amount,
 :old.old_amount,
 sysdate
);
end;
/

错误:

  SQL> show error
  Errors for TRIGGER AFTER_UPDATE:

  LINE/COL ERROR
  -------- --------------------------------------------------------------
   2/1   PL/SQL: SQL Statement ignored
   9/2   PL/SQL: ORA-01747: invalid user.table.column, table.column, or
         column specification

   13/2  PLS-00049: bad bind variable 'OLD.ID'
   14/2  PLS-00049: bad bind variable 'NEW.NAME'
   15/2  PLS-00049: bad bind variable 'OLD.OLD_NAME'
   16/2  PLS-00049: bad bind variable 'NEW.AMOUNT'
   17/2  PLS-00049: bad bind variable 'OLD.OLD_AMOUNT'
   SQL> 

1 个答案:

答案 0 :(得分:2)

您插入的值来自ACCOUNTS表,目标列来自ACCOUNT_HISTORY表。您将它们混在一起,这就是为什么会出现ORA-01747错误的原因。试试这个:

create or replace trigger after_update
    after update on accounts 
    referencing new as new old as old    
   for each row
 begin
     INSERT INTO account_history
       (
    id, 
    new_name,
    old_name,
    new_amount,
    old_amount,
    change_date
)
values
(
     :old.id,
     :new.name,
     :old.name,
     :new.amount,
     :old.amount,
     sysdate
    );
End;
/