MySQL触发器为NEW行设置值,并在同一表中更新另一个 [英] MySQL trigger set values for NEW row and update another in the same table
问题描述
我有一张桌子,可以跟踪特定项目的费用.这些费用会随着时间而变化,因此我有两列(startDate,endDate),当前的费用组在不久的将来总是具有endDate.我已经有一个触发器,可以用来对输入的新行进行一些计算,但是我还想发生的事情是,如果输入的条目已经有一个条目,我想将前一个条目的endDate设置为新条目的startDate和新endDate到预定的遥远日期.这是我首先尝试的代码:
I have a table that I keep track of fees for a specific item. These fees can change over time so I have two columns (startDate, endDate) with the current set of fees always having an endDate in the far future. I already have a trigger that I use to do some calculations on the new row being entered but what I also want to have happen is if I enter an item that already has an entry I want to set the previous entry's endDate to the day before the new entry's startDate and the new endDate to a predetermined far-away date. Here is the code for what I tried first:
CREATE
DEFINER=`root`@`%`
TRIGGER `im`.`splitBeforeIns`
BEFORE INSERT ON `im`.`split`
FOR EACH ROW
BEGIN
SET NEW.tcPercent = (NEW.tcOfficeFee / NEW.globalFee) * 100 , NEW.proPercent = 100 - NEW.tcPercent, NEW.endDate = 20501231;
UPDATE im.split set endDate = ADDDATE(NEW.startDate, -1) where procKey = NEW.procKey AND endDate = 20501231;
END$$
我得到的错误是:
ERROR 1442: Can't update table 'split' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
推荐答案
对此的答案可能不受欢迎,但这是:您不能这样做.
The answer to this might be unwelcome, but it is: You can't do that.
触发器不能更新同一表的另一行,因为该行是从中调用触发器的行.
A Trigger can't update another row of the same table as the row, the trigger was called from.
执行此操作的典型方法是创建一个存储过程,该过程将插入/更新目标表,然后更新其他行,所有这些都在事务中完成.
The typical way to do that, is to create a stored procedure, that inserts into/Updates the target table, then updates the other row(s), all in a transaction.
这篇关于MySQL触发器为NEW行设置值,并在同一表中更新另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!