chemicalkt
chemicalkt

Reputation: 816

create trigger by checking the value of a field being inserted in oralce

I need to create a before insert trigger on TABLE1 such that it inserts COL2 and COL3 of the new row being inserted in TABLE1 into TABLE2 only when TABLE1.FIELD1 = 'XYZ'. How do I do this so that trigger gets fired only when the condition is met?

Upvotes: 0

Views: 1694

Answers (1)

schurik
schurik

Reputation: 7928

CREATE OR REPLACE TRIGGER my_trigger
   before insert 
   ON table_1
   FOR EACH ROW
BEGIN
  IF :NEW.FIELD1 = 'XYZ'
  then
    INSERT INTO table_2 (col1, col2) VALUES (:NEW.col1, :NEW.col2);
  END IF;
END;
/

or how a_horse_with_no_name noted, your can use the the WHEN clause

CREATE OR REPLACE TRIGGER my_trigger
   before insert 
   ON table_1
   FOR EACH ROW
   WHEN (NEW.FIELD1 = 'XYZ') 
BEGIN

    INSERT INTO table_2 (col1, col2) VALUES (:NEW.col1, :NEW.col2);

END;
/

Upvotes: 1

Related Questions