想要编写更新和插入的触发器

时间:2014-06-25 08:41:56

标签: sql sql-server triggers

我有3张桌子:

  1. item(id,itemname)
  2. stock(stockid,stockquantity,itemid)
  3. sale(saleid,salenumber,itemid)
  4. 所以我必须以这样的方式编写一个触发器:如果插入任意数量的项目的销售,它会自动更新库存表中的库存量。并且它将减去之前的stockqty记录并更新它。

1 个答案:

答案 0 :(得分:0)

您可以为您的想法使用多个触发器:

CREATE TRIGGER YourInserttriggername ON Sale 
AFTER INSERT
AS BEGIN
    UPDATE stock
    SET StockQuantity = StockQuantity + SUM(Inserted.SaleNumber)
    FROM Inserted 
    WHERE Stock.ItemId = Inserted.ItemId
    GROUP BY Inserted.ItemId
END   


CREATE TRIGGER YourUpdatetriggername ON Sale 
AFTER Update
AS BEGIN
    UPDATE stock
    SET StockQuantity = StockQuantity + SUM(Inserted.SaleNumber - Deleted.SaleNumber)
    FROM Inserted 
    INNER JOIN Deleted ON Deleted.Id = Inserted.Id
    WHERE Stock.ItemId = Inserted.ItemId
    GROUP BY Inserted.ItemId
END


CREATE TRIGGER YourUpdatetriggername ON Sale 
AFTER Delete
AS BEGIN
    UPDATE stock
    SET StockQuantity = StockQuantity - SUM(Deleted.SaleNumber)
    FROM Deleted 
    WHERE Stock.ItemId = Deleted.ItemId
    GROUP BY Deleted.ItemID
END