0

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

我的更新触发器运行正常,但问题在于运行 MySQL 准备语句的应用程序似乎使用相同的信息多次更新表(该程序不是开源的,我无法更改 mysql 调用)。所以很明显会发生什么是我的发票触发器每次运行并抛出我的算法来扣除捆绑产品中包含的每个产品的 Product.Quantity。在下面的示例中,如果 Invoice 用于 Box 2,则 Product 523 的 Quantity 应减去 25。由于 Prepared 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 之前使用了上述“准备好的语句”,在 Trigger 上执行了 2 次迭代,导致我对库存的扣除倾斜?

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

4

1 回答 1

0

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

IF NEW.Status <> OLD.Status THEN
    -- DO SOMETHING IMPORTANT!
END IF;
于 2013-07-31T22:13:02.993 回答