Hi @Analyst_SQL
Try this:
CREATE OR ALTER TRIGGER [dbo].SO_QTY
ON OrderDetail
AFTER INSERT,DELETE,UPDATE
AS
BEGIN
WITH CTE AS
(SELECT OrderNO,SUM(QTY)AS QTY
FROM (SELECT OrderNO,SUM(ISNULL(orderqty,0))AS QTY FROM inserted I GROUP BY OrderNO
UNION
SELECT OrderNO,SUM(ISNULL(orderqty,0)) * (-1) FROM deleted D GROUP BY OrderNO
)U
GROUP BY OrderNO
)
UPDATE SalesOrder
SET O_QTY = ISNULL(O_QTY,0)+ISNULL(QTY,0)
FROM SalesOrder S LEFT JOIN CTE C ON S.OrderNo=C.OrderNO
END
Best regards,
Cosmog Hong
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.