简体   繁体   中英

update statement in Insert trigger on the same table

I want to write a trigger that includes an UPDATE statement on the same table, like this:

create trigger AFTER INSERT ON myTable
   FOR EACH ROW BEGIN
    update myTable set ... where ...
   end

How can I do this?

Quoting MySQL docs :

A trigger can also affect other tables, but it is not permitted to modify a table that is already being used (for reading or writing) by the statement that invoked the function or trigger.

You can do this (update the table that has triggered the after-insert trigger) BUT to avoid recursion, your FOR INSERT and FOR UPDATE trigger must be separate procedures. The other issue is that Microsoft SQL Server calls the FOR UPDATE trigger only once for any update statement. There is no FOR EACH ROW in SQL Server. Use a single UPDATE... table... WHERE statement inside your FOR INSERT TRIGGER to update a lot of rows at the same time.

I think it is not possible.

I create one table script is given below

CREATE TABLE `tbl1` (
    `id` INT(10) NULL DEFAULT NULL,
    `msg` VARCHAR(50) NULL DEFAULT NULL
)

Then i created trigger on that table using following query

delimiter |
create trigger trigger1 before insert on tbl1 for each row begin
update tbl1 set msg='insert occured in tbl1' where id=5;
end
|
delimiter ;

when i try to run following query

insert into tbl1 values (1,'ddd');

I got following error

"Cant update table 'tbl1' in stored function/trigger because it is already used by statement which invoked this stored function/trigger"

So its not possible. For more info visit http://bugs.mysql.com/bug.php?id=50684

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