【问题标题】:Two triggers and I am getting an error when updating table两个触发器,更新表时出现错误
【发布时间】:2012-12-03 13:25:06
【问题描述】:

我得到了以下两个触发器,每个触发器都单独工作,但它们不能一起工作。

我怎样才能让它们一起工作?它们更新表中的不同字段。

触发器 1:

create trigger wys_sk_u after update on `things`
for each row
begin
UPDATE `current` s 
INNER JOIN things u ON s.id_thing = u.id_thing
INNER JOIN dude_base b ON b.id= s.id
SET s.`curr_cash` = u.cash1 * b.cash2/ 100;
end;
$$

触发器 2:

create trigger suma_u after update on `current`
for each row
begin
UPDATE `current`
SET `mysum` = `curr_cash` + `mysum`;
end;
$$

当cash1 或cash2 更新时,第一个应该更新,并更改curr_cash 的值。 第二个应该在curr_cash更新时更新,并更改mysum。

编辑表格内容时出现以下错误:

#1442 - Can't update table 'current' in stored function/trigger because it is already used by statement which invoked this stored function/trigger. 

@编辑 为问题添加了新的答案。


如果我想做这样的事情怎么办:

CREATE TRIGGER total BEFORE UPDATE ON `current` FOR EACH ROW
BEGIN
if new.`new_pay_date` <> old.`new_pay_date`
  SET new.`total_cash` = new.`curr_cash` + new.`total_cash`;
end if;
END;
$$

错误:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET new.`total_cash` = new.`curr_cash` + new.`total_cash`; end if;' at line 4

这在没有

的情况下工作
if new.`new_pay_date` <> old.`new_pay_date`
end if;

但我需要检查这一点,并且只更新日期更改。

当前表:

curr_cash
new_pay_date
id_person
id_thing
total_cash

有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: mysql sql triggers


    【解决方案1】:

    问题出在第二个触发器上。尝试使用 BEFORE UPDATE 触发器使用 SET 语句更改字段值 -

    CREATE TRIGGER suma_u BEFORE UPDATE ON `current` FOR EACH ROW
    BEGIN
      SET new.`mysum` = new.`curr_cash` + new.`mysum`;
    END;
    

    【讨论】:

      【解决方案2】:

      无法更新在触发器中为其创建触发器的表。 MySQL 有加锁机制,无法更新触发触发器的同一张表的行,会导致递归调用触发器和无限循环。

      【讨论】:

        猜你喜欢
        • 2021-11-13
        • 2015-07-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-01
        • 1970-01-01
        相关资源
        最近更新 更多