Track inserts, updates, and deletes with OUTPUT
Use inserted and deleted row images to record exactly what a data change changed.
What you are trying to do
A small inventory workflow adds one item, raises a low quantity, removes a retired item, and collects each change into a local review table.
Work through it
- Read the starting rows in the local inventory table.
- For INSERT, trace the new row through inserted. For UPDATE, compare deleted with inserted. For DELETE, trace the removed row through deleted.
- Read the collected change rows in a stable order, then inspect the final inventory.
- The only writes target local temporary objects created by this script.
Check your work
The change log has three rows: INSERT item 3 with new quantity 9, UPDATE item 2 from 2 to 3, and DELETE item 1 with old quantity 5. The final inventory has item 2 at quantity 3 and item 3 at quantity 9.
Practice SQL
Open in SQL FlowCREATE TABLE #Inventory (ItemId int NOT NULL PRIMARY KEY, Quantity int NOT NULL);
DECLARE @Changes TABLE (ActionName nvarchar(10), ItemId int, OldQuantity int NULL, NewQuantity int NULL);
INSERT INTO #Inventory (ItemId, Quantity) VALUES (1, 5), (2, 2);
INSERT INTO #Inventory (ItemId, Quantity)
OUTPUT N'INSERT', inserted.ItemId, CAST(NULL AS int), inserted.Quantity INTO @Changes (ActionName, ItemId, OldQuantity, NewQuantity)
VALUES (3, 9);
UPDATE #Inventory
SET Quantity = Quantity + 1
OUTPUT N'UPDATE', inserted.ItemId, deleted.Quantity, inserted.Quantity INTO @Changes (ActionName, ItemId, OldQuantity, NewQuantity)
WHERE Quantity <= 2;
DELETE FROM #Inventory
OUTPUT N'DELETE', deleted.ItemId, deleted.Quantity, CAST(NULL AS int) INTO @Changes (ActionName, ItemId, OldQuantity, NewQuantity)
WHERE ItemId = 1;
SELECT ActionName, ItemId, OldQuantity, NewQuantity FROM @Changes ORDER BY ItemId;
SELECT ItemId, Quantity FROM #Inventory ORDER BY ItemId;
DROP TABLE #Inventory;
Knowledge check
Commands in this lesson
Next lesson Roll back the whole unit of work on error