Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't update table that trigger is executed on in AFTER INSERT

Tags:

mysql

triggers

I'm running MySQL 5.5.9 and InnoDB.

I try to create a versioned table, where the current field indicates whether a record is the most recent version. Something like:

| autonumber | id | name | current
| 1          | 1  | Yes  | 0
| 2          | 1  | No   | 1

Anyhow, I did this in the past in MSSQL quite often via an AFTER INSERT trigger that updates all records with the same id to current = 0. So here we go in MySQL:

DELIMITER |

CREATE TRIGGER TRIGGER_Products_UpdateEarlierVersions AFTER INSERT ON Products
FOR EACH ROW BEGIN
    UPDATE Products
    SET current = 0
    WHERE   id = new.id
        AND current = 1
        AND autonumber <> new.autonumber;
END;
|

This runs fine, but when inserting a record:

insert into Products (id, name)
values (1, "Hello SO!");

I get the following error:

Error Code: 1442. Can't update table 'Products' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

Is there a way around this to achieve a similar thing?

like image 990
Jan Jongboom Avatar asked Feb 10 '12 11:02

Jan Jongboom


People also ask

Can we update in after insert trigger?

You can not create an AFTER trigger on a view. You can not update the NEW values. You can not update the OLD values.

Does after update trigger fire on insert?

If a trigger is defined as AFTER UPDATE it does NOT fire after an INSERT.

Does update trigger fire on insert Salesforce?

Implementing the Triggers in Salesforce. Upsert triggers fire each before and once insert or before and after update triggers as applicable. Merge triggers fire each before and after delete for the losing records, and both before and after update triggers for the winning record.

How can create trigger on insert update and delete in SQL Server?

To test the trigger we can use the code below. INSERT INTO dbo. NestingTest (Test) VALUES (0); UPDATE dbo. NestingTest SET Test = 1 WHERE NestingTestID = 1; DELETE FROM dbo.


1 Answers

Taken from here http://forums.mysql.com/read.php?99,122354,122505#msg-122505

when you insert a record mysql is doing some lock stuff. you can't insert/update/delete rows of the same table where you insert.. because then the trigger would called again and again.. ending up in a recursion

like image 110
Sergey Benner Avatar answered Sep 30 '22 05:09

Sergey Benner