ORACLE and TRIGGERS (inserted, updated, deleted)

后端 未结 4 781
小鲜肉
小鲜肉 2020-12-14 02:00

I would like to use a trigger on a table which will be fired every time a row is inserted, updated, or deleted.

I wrote something like this:

CREATE o         


        
相关标签:
4条回答
  • 2020-12-14 02:08

    Separate it into 2 triggers. One for the deletion and one for the insertion\ update.

    0 讨论(0)
  • 2020-12-14 02:17

    From Using Triggers:

    Detecting the DML Operation That Fired a Trigger

    If more than one type of DML operation can fire a trigger (for example, ON INSERT OR DELETE OR UPDATE OF Emp_tab), the trigger body can use the conditional predicates INSERTING, DELETING, and UPDATING to check which type of statement fire the trigger.

    So

    IF DELETING THEN ... END IF;
    

    should work for your case.

    0 讨论(0)
  • 2020-12-14 02:18

    I've changed my code like this and it works:

    CREATE or REPLACE TRIGGER test001
      AFTER INSERT OR UPDATE OR DELETE ON tabletest001
      REFERENCING OLD AS old_buffer NEW AS new_buffer 
      FOR EACH ROW WHEN (new_buffer.field1 = 'HBP00' OR old_buffer.field1 = 'HBP00') 
    
    DECLARE
          Operation       NUMBER;
          CustomerCode    CHAR(10 BYTE);
    BEGIN
    
    IF DELETING THEN 
      Operation := 3;
      CustomerCode := :old_buffer.field1;
    END IF;
    
    IF INSERTING THEN 
      Operation := 1;
      CustomerCode := :new_buffer.field1;
    END IF;
    
    IF UPDATING THEN 
      Operation := 2;
      CustomerCode := :new_buffer.field1;
    END IF;    
    
    // DO SOMETHING ...
    
    EXCEPTION
        WHEN OTHERS THEN ErrorCode := SQLCODE;
    
    END;
    
    0 讨论(0)
  • 2020-12-14 02:23

    The NEW values (or NEW_BUFFER as you have renamed them) are only available when INSERTING and UPDATING. For DELETING you would need to use OLD (OLD_BUFFER). So your trigger would become:

    CREATE or REPLACE TRIGGER test001
      AFTER INSERT OR DELETE OR UPDATE ON tabletest001
      REFERENCING OLD AS old_buffer NEW AS new_buffer 
      FOR EACH ROW WHEN (new_buffer.field1 = 'HBP00' OR old_buffer.field1 = 'HBP00') 
    

    You may need to add logic inside the trigger to cater for code that updates field1 from 'HBP000' to something else.

    0 讨论(0)
提交回复
热议问题