Handling multiple rows in SQL Server trigger

前端 未结 3 2066
一向
一向 2020-12-19 03:00

We have a database with a table called WarehouseItem where product\'s stock levels are kept. I need to know when ever this table get\'s updated, so I create

3条回答
  •  [愿得一人]
    2020-12-19 03:54

    You use this:

    -- Get Product Id
    DECLARE @StockItemID INT = (SELECT ItemID FROM INSERTED);
    DECLARE @WarehouseID INT = (SELECT WarehouseID FROM INSERTED);
    

    But if you update multi rows (as your sample) you must use a different strategy.

    For example, instead to declare a variable, use INSERTED table in JOIN in query where now you use your variable.

    IF statement works on your variable but I think to move that condition in query.

    Try to change you UPDATE query in this way (eventually add condition of IF):

    -- Reset [StockUpdate] Queue Entry
    UPDATE IC_StockUpdateQueue SET Synced = 0
    FROM inserted 
    WHERE inserted.itemID = StockItemID;
    

    And so on.

    For further information please add comment.

提交回复
热议问题