sqloracle-databasetriggerssql-updatesql-insert

trigger to update specific column when insert/update happened in same table


I trying to write a trigger that will update a column when user insert or updates a row, within the same table. Example: insert into user(ID, F_NM, L_NM, EMAIL) values ('1', 'John','Doe','john.doe@market.org.com'); after the insert, i want to call: update user set ORG = 'market' where ID = '1'.

create or replace trigger user_change
after insert or update of EMAIL on USER
for each row
declare
  NEW_ORG VARCHAR(10);
BEGIN
  CASE
    when :NEW.EMAIL like '$@market.org.com' then
      NEW_ORG := 'market';
    ........
  END CASE;

  UPDATE USER set ORG = NEW_ORG where ID = :NEW.ID
END;

Calculating the new ORG work, but I can't get the update statement to work. I get 'ORA-04091 table USER is mutating, trigger/funtion may not see it', figure its due to me inserting/updating the same record at same time. Tried adding 'pragma autonomous_transaction' and 'commit' to the trigger, the insert/update of fields works but the ORG does not get updated.

Also tried changing to INSTEAD OF INSERT OR UPDATE OF EMAIL but I keep getting 'ORA-04073 column list not valid for this trigger type'

create or replace trigger user_change
instead of insert or update of EMAIL on USER

while i get 'ORA-25002 cannot create instead of triggers on tables'

create or replace trigger user_change
instead of insert on USER

Solution

  • Why not simply turn the trigger to a before trigger, when you can set the value before it is written? This way, you don't need to run a new DML statement on the table, which avoid the "mutating" error.

    create or replace trigger user_change
    after insert or update of email on user
    for each row
    begin
        if :new.email like '%@market.org.com' then
            :new.org := 'market';
        end if;
    end;