更新旧表时触发将数据行插入新表

时间:2018-11-28 14:53:39

标签: oracle plsql database-trigger

只想在日志表中插入更新的行,但以下触发块却出错:

CREATE OR REPLACE TRIGGER system_notification_audit
  AFTER INSERT OR UPDATE on ncr_system_notification
  FOR EACH ROW
BEGIN
  insert into ncr_system_notification_log
  values
    (:NEW.ID,
     :NEW.NAME,
     :NEW.Description,
     :NEW.PREFERENCE,
     :NEW.FREQUENCY,
     :NEW.IS_HIGH,
     :NEW.IS_REQUIRED,
     :NEW.UPDATED_BY,
     :NEW.UPDATED_DATE) 
   where :OLD.IS_REQUIRED <> :NEW.IS_REQUIRED;
END;

2 个答案:

答案 0 :(得分:1)

执行此操作的标准方法是使用PL / SQL条件:

CREATE OR REPLACE TRIGGER system_notification_audit
 AFTER 
      INSERT OR 
      UPDATE 
on ncr_system_notification
FOR EACH ROW
begin

    if :OLD.IS_REQUIRED <> :NEW.IS_REQUIRED then
        insert into ncr_system_notification_log
        VALUES (:NEW.ID , :NEW.NAME, :NEW.Description, :NEW.PREFERENCE, :NEW.FREQUENCY, :NEW.IS_HIGH, :NEW.IS_REQUIRED, :NEW.UPDATED_BY, :NEW.UPDATED_DATE) ;     
    end if ;
END;

答案 1 :(得分:0)

insert语句中使用select

insert into ncr_system_notification_log 
select :NEW.ID , :NEW.NAME, :NEW.Description, :NEW.PREFERENCE, :NEW.FREQUENCY, 
       :NEW.IS_HIGH, :NEW.IS_REQUIRED, :NEW.UPDATED_BY, :NEW.UPDATED_DATE
  from dual
 where :OLD.IS_REQUIRED <> :NEW.IS_REQUIRED;

假设IS_REQUIRED可为空的非负整数列,则可以假定nvl函数第二个参数的负值为负整数例如不等式中的-1:

where nvl(:OLD.IS_REQUIRED,-1) <> nvl(:NEW.IS_REQUIRED,-1)