插入数据时触发更新库存清单

时间:2018-03-19 11:02:03

标签: sql sql-server triggers database-trigger

我在这上面看过几篇帖子,但在我的案例中仍有问题。我2桌SALES_STOCKS和股票。我想当有人从表SALES_STOCKS购买产品时(它有一列NUMBER_STOCKS),另一个表STOCKS来更新QUANTITY列。换句话说,它应该更新SALES_STOCKS.NUMBER_STOCKS - STOCKS.QUANTITY

以下是我的数据库的屏幕截图:

My database

这是我用触发器设法做的事情:

  CREATE TRIGGER trg_updStocks ON SALES_STOCKS
  AFTER INSERT AS
  BEGIN
      IF EXISTS(SELECT * FROM inserted
            LEFT OUTER JOIN deleted
            ON inserted.NUMBER_STOCKS = deleted.NUMBER_STOCKS
            WHERE deleted.NUMBER_STOCKS IS NULL)
      UPDATE STOCKS
      SET QUANTITY = QUANTITY - NEW.QUANTITY 
      WHERE ID = New.ID;
  END
  GO

1 个答案:

答案 0 :(得分:0)

deleted触发器中没有insert。 SQL Server触发器中没有new

我想你只是想:

CREATE TRIGGER trg_updStocks ON SALES_STOCKS
AFTER INSERT AS
BEGIN
  UPDATE s
      SET QUANTITY = QUANTITY - i.insert_quantity 
      FROM STOCKS s JOIN
           (SELECT i.stock_id, SUM(i.quantity) as insert_quantity
            FROM inserted i
            GROUP BY i.stock_id
           ) i
           ON s.ID = i.ID;
END;

对于更新和删除触发器,您可以在deleted表上使用类似的逻辑。