MySQL Update Trigger准备好的声明解决方法?

时间:2013-07-25 21:36:03

标签: mysql triggers prepared-statement

我正在为发票开发一个自定义触发器,它会在Invoice.ID上为每个更新的行捕获ID。 Invoice.ID将用于Query Orders.ID并选择Orders.Quantity和Orders.SKU。然后,我为Bundles中的每个Product.ID扣除Product.Quantity(即Bundle one由product1,product2和product3组成)

我的更新触发器正常运行但问题是运行MySQL预处理语句的应用程序似乎用相同的信息多次更新表(该程序不是开源的,我无法改变mysql调用)。所以很明显,我的Invoice触发器每次都会运行并抛出我的算术,以便为捆绑产品中包含的每个产品扣除Product.Quantity。在下面的示例中,如果发票用于方框2,则产品数量523应扣除25.由于准备好的mysql语句,触发器运行两次,而是扣除50个库存。请参阅下面的mysql.general.log。

AFTER UPDATE ON `myDB`.`Invoice`
  FOR EACH ROW
BEGIN

DECLARE invoice_id integer;
DECLARE order_status varchar(11);
DECLARE order_sku varchar(255);
DECLARE order_quantity integer;

SET invoice_id = (SELECT InvoiceID FROM Invoice WHERE InvoiceID = NEW.InvoiceID);
SELECT Status INTO order_status FROM Invoice WHERE InvoiceID = invoice_id;
SELECT SKU INTO order_sku FROM Orders WHERE InvoiceID = invoice_id  AND SKU LIKE '%Box%';
SELECT Quantity INTO order_quantity FROM Orders WHERE InvoiceID = invoice_id AND SKU LIKE '%Box%';

IF order_status = 'Ordered' THEN
   IF order_sku = 'Box 1' THEN
       UPDATE Product
       SET Quantity = CASE ProductNo
           WHEN 525 THEN (Quantity + (-3 * order_quantity))
           WHEN 523 THEN (Quantity + (-2 * order_quantity))
           WHEN 526 THEN (Quantity + (-1 * order_quantity))
           WHEN 524 THEN (Quantity + (-1 * order_quantity))
           WHEN 502 THEN (Quantity + (-2 * order_quantity))
           WHEN 515 THEN (Quantity + (-1 * order_quantity))
           WHEN 506 THEN (Quantity + (-2 * order_quantity))
           WHEN 520 THEN (Quantity + (-1 * order_quantity))
           WHEN 514 THEN (Quantity + (-1 * order_quantity))
           WHEN 532 THEN (Quantity + (-1 * order_quantity))
           WHEN 527 THEN (Quantity + (-1 * order_quantity))
           WHEN 497 THEN (Quantity + (-1 * order_quantity))
      END
      WHERE ProductNo IN (525, 523, 526, 524, 502, 515, 506, 520, 514, 532, 527, 497);
 END IF;

 IF order_sku = 'Box 2' THEN
  UPDATE Product
    SET Quantity = Quantity + (-25 * order_quantity)
    WHERE ProductNo = 523;
 END IF;

Mysql.General.Log

 47 Prepare     [12526] UPDATE Invoice SET InvoiceNo = ?, Status = ?...
 47 Execute     [12526] UPDATE Invoice SET InvoiceNo = 208048, Status = Ordered ....

这是理性思考吗,因为程序在更新Invoice之前使用上面的“预备语句”,在触发器上执行了2次迭代,导致我对库存的偏差扣除?

任何见解/帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

对于那些寻找类似解决方案的人来说,这一直非常简单并且在我面前。

IF NEW.Status <> OLD.Status THEN
    -- DO SOMETHING IMPORTANT!
END IF;