为同一个表创建条件更新的触发器

时间:2014-03-30 14:19:51

标签: mysql

 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):无法更新表格&#39;帐户&#39;在存储的函数/触发器中,因为它已被调用此存储函数/触发器的语句使用。

1 个答案:

答案 0 :(得分: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子句,这意味着您只是因为单行被更改而更新了整个表。