Mysql触发器返回1442错误

时间:2017-03-20 22:17:43

标签: mysql database triggers

我有order属性的测试表。当order更改其值时,我需要重新计算表中的所有order值。我有以下触发器:

DELIMITER $$

USE `testing`$$

DROP TRIGGER /*!50032 IF EXISTS */ `UpdateOrder`$$

CREATE
    /*!50017 DEFINER = 'root'@'localhost' */
    TRIGGER `UpdateOrder` AFTER UPDATE ON `upd_tst` 
    FOR EACH ROW BEGIN
    IF (OLD.order > NEW.order) THEN
        UPDATE `upd_tst` t SET t.`order` = t.`order` + 1 WHERE t.`order` < OLD.order AND t.`order` >= NEW.order AND t.id <> OLD.id;
    ELSEIF (OLD.order < NEW.order) THEN
        UPDATE `upd_tst` t SET t.`order` = t.`order` - 1 WHERE t.`order` > OLD.order AND t.`order` <= NEW.order AND t.id <> OLD.id;
    END IF;
    END;
$$

DELIMITER ;

当我尝试更新任何项目时,我收到nex错误:

Executed SQL Statement : update `testing`.`upd_tst` set `order`='3' where `id`='3' 
Error Number : 1442 
Error Message: Can't update table 'upd_tst' in stored function/trigger because it is already used by statement which invoked this stored function/trigger. 

我如何解决这个问题?我需要使用ONLY触发器。

在postgresql中,我可以在触发器WHEN (pg_trigger_depth() = 0)内使用此条件。在mysql中有这样的东西吗?

1 个答案:

答案 0 :(得分:0)

解决方案:将其设为BEFORE UPDATE ON触发器 - 这样您就可以在触发器SQL中设置/更新字段值:

DELIMITER $$
USE `testing`$$
DROP TRIGGER /*!50032 IF EXISTS */ `UpdateOrder`$$
CREATE
    /*!50017 DEFINER = 'root'@'localhost' */
    TRIGGER `UpdateOrder` BEFORE UPDATE ON `upd_tst` 
    FOR EACH ROW BEGIN
    IF (OLD.order > NEW.order) THEN
        SET NEW.order = NEW.order` + 1;
    ELSEIF (OLD.order < NEW.order) THEN
        SET NEW.order = NEW.order - 1;
    END IF;
    END;
$$
DELIMITER ;

原因:您无法更新/删除/插入调用触发器的表:

  

在存储的函数或触发器中,不允许修改a   已经被使用(用于读或写)的表   调用函数或触发器的语句。

这样做会产生错误1442:

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