无法更新触发器中的表
Posted
技术标签:
【中文标题】无法更新触发器中的表【英文标题】:Can't update table in trigger 【发布时间】:2012-11-21 17:28:24 【问题描述】:我做了一个新的触发器,它必须更新员工的工资。它从餐桌支付中获取 2 个值(现金和月份),并将它们分成“how_much_to_pay”列。
我看了题目: mysql triggers cannot update rows in same table the trigger is assigned to. Suggested workaround?
但这对我没有帮助,因为他们只使用一张桌子,他们可以毫无问题地放入“新”。
这是我的触发器:
create trigger pay_out before insert on `payment_out`
for each row
then
UPDATE `payment_out` o
INNER JOIN payment p ON p.id_1 = o.id_1 AND o.id2 = p.id2
SET o.`how_much_to_pay` = p.cash / p.months;
end;
$$
这里是表格:
table payment_out
id1
id2
how_much_to_pay
table payment
id1
id2
cash
months
以及错误本身:
1442 - Can't update table payment_out in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
【问题讨论】:
【参考方案1】:如果您在两个表之间存在一对一的关系,那么您可以在 BEFORE INSERT 触发器中使用此代码 -
BEGIN
SELECT p.cash, p.months INTO @cash, @months
FROM payment p
WHERE p.id_1 = NEW.id_1 AND p.id2 = NEW.id2;
SET NEW.how_much_to_pay = @cash / @months;
END
【讨论】:
好吧,这行得通,但“支付多少”为 NULL,即使现金 = 8000,月 = 8。 如果p.cash
或p.months
之一为NULL,则它可以为null。尝试从触发器运行 SELECT,将正确的值添加到 WHERE 条件。结果如何?
当我注意到它时,我将其更改为 0.00。以上是关于无法更新触发器中的表的主要内容,如果未能解决你的问题,请参考以下文章
如何解决错误 1442:无法更新 mysql 中存储的函数/触发器中的表 'tb_name'?
无法更新存储函数/触发器中的表“事务”,因为它已被调用此存储函数/触发器的语句使用
错误代码:1442。无法更新存储函数/触发器中的表“客户”,因为它已被调用此存储函数的语句使用