简体   繁体   中英

How to create a trigger which, update a row in the same table after insert?

For example, I have a table t_1 and I insert only id value, but trigger should after insert, update value id_2 and set id_2 to id :

create table t_1(
id number(10),
id_1 number(10)
);

I create trigger:

create or replace trigger id_to_id_2
after insert
on t_1
for each row
begin
update t_1 set id_2=:new.id where id = new.id;
end;

/

But when I try insert, I get the error:

    DB constraint error: ORA-04091: table t_1is mutating, trigger/function may 
not see it\nORA-06512: at 

I don't understand the error, could you explain me what am I doing wrong?

You need a before insert trigger like this:

create or replace trigger id_to_id_2
before insert
on t_1
for each row
begin
  :new.id_2 := :new.id;
end;

A similar question has been asked here: Table is mutating, trigger/function may not see it (stopping an average grade from dropping below 2.5) and here: https://dba.stackexchange.com/questions/5432/what-are-the-causes-and-solutions-for-mutating-table-errors

Probably the trigger isn't the right way to do what you want to achieve. At least, as the second link says, the outcome of your instructions isn't predictable in all possible cases. If the links cited above do not help you, I suggest you give more information about your intentions.

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