Reputation: 5
I have two tables:
Table Order
: IDOrder (PK), ProductId, Quantity, Price
Table Product
: ProductId (PK), Name,...., Quantity
I want to change quantity of product table when quantity of order table was added. But this does not work.
Here is my trigger:
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
Upvotes: 0
Views: 928
Reputation: 1728
Try This
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
Upvotes: 1