我有两张桌子:
表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
答案 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