使用触发器更新2个表

时间:2017-12-05 12:12:24

标签: sql-server triggers

我有两张桌子:

  • Order:IDOrder(PK),ProductId,Quantity,Price

  • Product:ProductId(PK),名称,......,数量

我想在订单表的数量添加时更改产品表的数量。但这不起作用。

这是我的触发器:

CREATE TRIGGER [dbo].[trg_updatequantity]
On [dbo].[order]
FOR UPDATE
AS
    IF UPDATE(quantity)
       UPDATE product 
       SET product.quantity = product.quantity - (inserted.quantity - deleted.quantity)
       FROM (deleted 
       INNER JOIN inserted ON deleted.IDOrder = inserted.IDOrder) 
       INNER JOIN product ON product.productId = inserted.ProductId

1 个答案:

答案 0 :(得分:1)

试试这个

Create trigger [dbo].[trg_updatequantity]
On [dbo].[order]
FOR INSERT
AS

update product SET quantity= a.quantity - b.quantity
from product a 
inner join (
    SELECT  ProductID, SUM( ISNULL( quantity, 0))quantity 
    FROM    inserted 
    GROUP BY ProductID) b 
ON  a.ProductID = b.ProductID