Mysql can't update rows when my trigger is called

偶尔善良 提交于 2019-12-12 00:46:53

问题


My trigger fails when i try to insert a new row in my table because Mysql doesn't support updating rows in the same table the trigger is assigned to. Does anyone have suggestions on a good workaround/alternative?

My trigger:

-- Trigger DDL Statements
DELIMITER $$

CREATE TRIGGER check_sequence
BEFORE INSERT ON data FOR EACH ROW
BEGIN 
    IF EXISTS(SELECT TRUE FROM data WHERE sequence = NEW.sequence) THEN
        UPDATE data SET sequence=sequence+1 WHERE sequence >= NEW.sequence;
    END IF;
END $$
DELIMITER ;

Error Sql that is displayed when i try to insert new row:

ERROR 1442 (HY000): Can't update table 'data' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

Thanks for answer,


回答1:


In MySQL, You can't update (or insert in) table A in a trigger for table A.

http://dev.mysql.com/doc/refman/5.0/en/stored-program-restrictions.html

You can try a sproc and use a transaction, or consider PostgreSQL, which can do this.



来源:https://stackoverflow.com/questions/17252473/mysql-cant-update-rows-when-my-trigger-is-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!