Question

I've created a trigger as follows:

create or replace trigger "PASSENGERS_BACKUP_T1"
after
insert or update or delete on "PASSENGERS"
for each row
begin
    if :NEW."P_ID" is  NOT null then 
        INSERT INTO PASSENGERS_BACKUP(
            PB_ID,
            PB_FIRST_NAME,
            PB_LAST_NAME,
            PB_STREET_ADDRESS1,
            PB_STREET_ADDRESS2,
            PB_CITY,
            PB_STATE,
            PB_POSTAL_CODE,
            PB_EMAIL,
            PB_PHONE_NUMBER1,
            PB_PHONE_NUMBER2,
            PB_URL,
            PB_CREDIT_LIMIT,
            PB_TAGS)
        VALUES (
            :new.P_ID,
            :new.P_FIRST_NAME,
            :new.P_LAST_NAME,
            :new.P_STREET_ADDRESS1,
            :new.P_STREET_ADDRESS2,
            :new.P_CITY,
            :new.P_STATE,
            :new.P_POSTAL_CODE,
            :new.P_EMAIL,
            :new.PHONE_NUMBER1,
            :new.PHONE_NUMBER1,
            :new.URL,
            :new.CREDIT_LIMIT,
            :new.TAGS);
    end if;
end;

now, when I update​ an existing row in "passengers" table as per the above trigger another new row is getting added in "passengers_backup" table instead I would like to update the existing row whenever an update is done in "passengers" table rows. As, well If I delete a row in "Passengers" table, if that row exists in 'Passengers_backup' table it should also get deleted. How can I acheive this?

Thanks in advance.

Was it helpful?

Solution

For solving your problem you need to use trigger with corresponding SQL statement for each action: insert, update, delete. As variant you can use something like this (Note, I left only two columns from your example for readability, so modify your trigger as you need):

create or replace trigger "PASSENGERS_BACKUP_TIUD"
    after insert or update or delete on "PASSENGER"
for each row
begin
    if inserting then
          insert into "PASSENGER_BACKUP" (pb_id, pb_first_name)
          values (:NEW.pb_id, :NEW.pb_first_name);
    elsif updating then
          update "PASSENGER_BACKUP"
          set pb_id=:NEW.pb_id, pb_first_name=:NEW.pb_first_name
          where pb_id=:NEW.pb_id;
    elsif deleting then
          delete from "PASSENGER_BACKUP"
          where pb_id=:OLD.pb_id;
    end if;
end;

Also you can see work of this trigger in action on SQL Fiddle.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top