简体   繁体   中英

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

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;

Looks like your org column can be calculated virtual column. In this case it would be better to create user-defined deterministic pl/sql function that returns correct calculated value and add it to your table, for example:

Alter table t add org varchar2(30) generated always as (f_get_org(email))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM