【问题标题】:create a trigger to for conditional update on same table创建触发器以在同一张表上进行条件更新
【发布时间】:2014-03-30 14:19:51
【问题描述】:
 delimiter //
 create trigger T1 before update on account
     for each row
        if NEW.balance <= 0 then
          update account set balance=OLD.balance;
       end if;
     //
Query OK, 0 rows affected (0.09 sec)

 delimiter ;
 update account set balance=-1 where id=101;

错误 1442 (HY000):无法更新存储函数/触发器中的表“帐户”,因为它已被调用此存储函数/触发器的语句使用。

【问题讨论】:

标签: mysql


【解决方案1】:

MySQL 使用行级触发器,因此触发器会针对正在更改的每一行触发。因此没有理由更新目标表,只需分配值:

create trigger T1 before update on account
 for each row
    if NEW.balance <= 0 then
      set new.balance = OLD.balance; -- this is the difference
   end if;

SQLFiddle 示例:http://sqlfiddle.com/#!2/34aebb/1


您的更新无论如何都不会起作用,因为它缺少一个 where 子句,这意味着您将更新 整个 表,只是因为更改了一行。

【讨论】:

    猜你喜欢
    • 2019-08-20
    • 2011-03-07
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    • 2016-12-14
    • 2021-12-13
    相关资源
    最近更新 更多