【问题标题】:Why trigger is doing unnecessary subtraction after a query in sql?为什么触发器在sql中的查询后进行不必要的减法?
【发布时间】:2021-04-16 04:33:20
【问题描述】:

我有两张桌子:

  1. 订购和
  2. 产品。

我希望 Product 表中的特定列 (OnShelfQuantity) 在 Order 表中添加新行时更新。我已经使用下面的查询来实现一个触发器,它将做到这一点。但问题是,当我在 Order 表中插入一行,然后检查 Product 表以查看更改时,我注意到 Product 表已更新 3 次。例如:插入的订单数量 = 10,则只需从 Product_TAB.OnShelfQuantity 中减去 10。但是30被减去。请帮忙!

create trigger dbo.Trigge
ON dbo.Ordertable
AFTER INSERT 
AS
BEGIN
update Product_TAB set OnShelfQuantity= Product_TAB.OnShelfQuantity - Ordertable.Quantity
FROM dbo.Product_TAB
  INNER JOIN Ordertable
  ON Ordertable.ProductID = Product_TAB.ProductID;
END;

【问题讨论】:

  • 您使用的是哪个 dbms? (该代码是特定于产品的。)
  • @jarth 它的 SQL 服务器,我正在使用 SSMS 来实现代码。
  • Product 表已经更新了 3 次 ... 那么 Ordertable 对于给定的 ProductID 是否有三行?您可能想阅读触发器中使用的inserted and deleted virtual tables
  • 这个触发器可能最好用索引视图实现
  • 您想解决您的问题吗?

标签: sql-server tsql triggers


【解决方案1】:

我认为,您可以使用 INSERTED 表来解决此问题。

插入表是触发器用来存储表中经常插入的记录的表。

因此,您可以在更新语句中使用相同的内容来避免这种情况。

update Product_TAB set OnShelfQuantity= Product_TAB.OnShelfQuantity - 
Ordertable.Quantity
FROM dbo.Product_TAB
INNER JOIN Ordertable  ON Ordertable.ProductID = Product_TAB.ProductID
INNER JOIN inserted INS ON INS.Order_ID=Ordertable.Order_ID

【讨论】:

  • 没有理由加入订单表 - 您需要的一切都在 AFTER 触发器中的插入表中。
【解决方案2】:

inserted 表中可以有多行。并且,这些行可能具有相同的产品。目标表中的一行仅在update 语句中更新一次。因此,您希望在update 之前聚合数据:

create trigger dbo.Trigge
ON dbo.Ordertable
AFTER INSERT 
AS
BEGIN    
    update p
        set OnShelfQuantity= p.OnShelfQuantity - i.total_quantity
        from dbo.Product_TAB p JOIN
             (SELECT i.ProductId, SUM(i.Quantity) as total_quantity
              FROM inserted i
              GROUP BY i.ProductId
             ) i
             on i.ProductID = p.ProductID;
END;

请注意,这仅使用inserted 而不是原始表。

【讨论】:

    【解决方案3】:

    所以问题是我正在插入新行但具有相同的订单 ID。这就是为什么它做了我不需要的额外减法。所以现在我必须插入一个新行但具有唯一的 OrderID。感谢以上所有回复的人!

    【讨论】:

      猜你喜欢
      • 2012-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-07
      • 1970-01-01
      • 2012-11-14
      • 2017-07-27
      • 1970-01-01
      相关资源
      最近更新 更多