简体   繁体   中英

Execute a trigger on the same table if updating

I need to execute a trigger that includes an UPDATE statement on the same table.

I have tried this code. If I check the table, the row is updated, but I get an error message:

Can't update table 'Orders' in stored function/trigger because it is already used by statement which invoked this stored function/trigger

DROP TRIGGER IF EXISTS UpdateTotal;

DELIMITER |

CREATE TRIGGER UpdateTotal BEFORE UPDATE ON Orders
FOR EACH ROW 
BEGIN
  UPDATE Orders P1
    SET NEW.order_total = NEW.order_total + 3.02
    WHERE order_id IN (SELECT * FROM (SELECT MAX(order_id) FROM Orders) P2);
END

|

DELIMITER ;

you can't do all this in a trigger. According to the documentation :

Within a stored function or trigger, 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.

explain more about requirement and table structure.

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