Search code examples
oracleplsqltriggers

PL/SQL trigger to update another table(using primary keys) for insert on one table


Scenario is,

TableA schema:

 PK(col_1, col_2, col_3), col_4, col_5
 col_1 VARCHAR2(2)
 col_2 VARCHAR(16)
 col_3 VARCHAR(3)
 col_4 NUMBER
 col_5 NUMBER

TableB schema:

 PK(col_1, col_2, col_3), col_4, col_5, col_6
 col_1 VARCHAR2(2)
 col_2 VARCHAR(16)
 col_3 VARCHAR(3)
 col_4 NUMBER
 col_5 NUMBER
 col_6 CHAR(1)
 col_7 CHAR(1)

Trigger update on TableB for every row insert in TableA

Primary keys for TableA and TableB has same composite keys - PK(col_1, col_2, col_3).

First 5 columns of TableA & TableB are same.


Question:

In Oracle DB, How to use primary key values of TableA row to update corresponding row in TableB? in below code...

CREATE OR REPLACE TRIGGER trigger_tableA
  BEFORE INSERT ON TableA
  FOR EACH ROW
DECLARE
BEGIN
  UPDATE TableB
  SET col_6 = 'Y'
  SET col_7 = 'Y'
  WHERE <use primary keys of inserted record in TableA>;
END trigger_tableA;
/

Solution

  • I'd use merge.

    create or replace trigger trigger_table1
      before insert on tablea
      for each row
    begin
      merge into tableb b
      using tablea a
      on (    a.col1 = b.col1
          and a.col2 = b.col2
          and a.col3 = b.col3
         )
      when matched then update set
        b.col6 = 'Y',
        b.col7 = 'Y';
      where b.col1 = :new.col1
        and b.col2 = :new.col2
        and b.col3 = :new.col3;
    end;
    /
    

    [EDIT] On a second thought, maybe your update attempt even makes more sense then my merge. Though, should be correctly written as

    create or replace trigger trigger_table2
      before insert on tablea
      for each row
    begin
      update tableb b set
        b.col6 = 'Y',
        b.col7 = 'Y'
      where b.col1 = :new.col1
        and b.col2 = :new.col2
        and b.col3 = :new.col3;
    end;
    /
    

    [EDIT #2] If you want, you can combine different options within the same trigger. You'd use IF-THEN-ELSE, e.g.

    create or replace trigger trigger_table2
      before insert or update or delete on tablea
      for each row
    begin
      if inserting then
         update tableb b set
           b.col6 = 'Y',
           b.col7 = 'Y'
         where b.col1 = :new.col1
           and b.col2 = :new.col2
           and b.col3 = :new.col3;
      elsif updating then
         update tableb b set
           b.col6 = 'N',
           b.col7 = 'Y'
         where b.col1 = :new.col1
           and b.col2 = :new.col2
           and b.col3 = :new.col3;
      elsif deleting then
         update tableb b set
           b.col6 = 'N',
           b.col7 = 'N'
         where b.col1 = :new.col1
           and b.col2 = :new.col2
           and b.col3 = :new.col3;
      end if;
    end;
    /