如何添加数据以从最后一次插入触发

时间:2019-05-15 22:09:39

标签: sql sql-server triggers

我面临以下情况:

enter image description here

我创建了一个触发器,该触发器在插入到第三张表时做出反应。当我插入任何数据(例如1 1 2)时,应从单元格的“库存量”列中减去最后一个数字,该数字必须为ID Product(如图所示)。但是我怎么才能知道最后添加的是哪一行呢?我以为首先要通过选择来完成,但是似乎不可能。现在我认为可以在游标的帮助下完成此操作,但它似乎并不是最好的选择。请问有更好的选择吗?

这是我的触发器代码,但不幸的是,每次仅从第一乘积中减去1。

CREATE TRIGGER AmountInsert ON Amount
AFTER INSERT
AS
BEGIN
    UPDATE Product
    SET Amount_On_Stock =
     (SELECT Amount_On_Stock FROM Product
    WHERE ID_Product = 1) - 1
    WHERE ID_Product = 1
END

1 个答案:

答案 0 :(得分:1)

您需要了解的第一件事是,在SQL Server的触发器中,您提供了inserted pseudo-table and a deleted pseudo-table。您可以使用这些表来确定发生了什么更改。

我认为以下触发器可以满足您的需求-这些注释说明了逻辑。

CREATE TRIGGER dbo.AmountInsert ON dbo.Amount
AFTER INSERT
AS
BEGIN
  set nocount on;

  update P set
    -- Adjust the stock level by the amount of the latest insert
    Amount_On_Stock = coalesce(Amount_On_Stock) - I.Amount
  from dbo.Product P
  inner join (
    -- We need to group by ID_Product in case the same product appears in the insert multiple times
    select ID_Product, sum(Amount) Amount
    from Inserted
    group by ID_Product
    -- No need to update is net change is zero
    having sum(Amount) <> 0
  ) I
  on I.ID_Product = P.ID_Product;
END