Update Selected SQL Server Rows and Verify the Result
An UPDATE changes every row satisfying its predicate. A missing or overly broad WHERE clause can therefore change far more than intended. Start with an exact key and expected current value, inspect the changes, and separate rehearsal from a committed production operation.
Prepare and Preview Disposable Rows
Run the whole example in a fresh session without an existing transaction:
CREATE TABLE #Stock
(
ProductId int NOT NULL PRIMARY KEY,
Quantity int NOT NULL
);
INSERT #Stock VALUES (1, 10), (2, 20);
SELECT ProductId, Quantity
FROM #Stock
WHERE ProductId = 1 AND Quantity = 10;
The preview returns exactly product 1 with quantity 10. The current-value condition is intentional. On a real table, it can help detect a conflicting change rather than blindly overwrite it.
Apply, Inspect and Roll Back
Continue in the same session:
SET XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION;
UPDATE #Stock
SET Quantity = 12
OUTPUT inserted.ProductId,
deleted.Quantity AS PreviousQuantity,
inserted.Quantity AS NewQuantity
WHERE ProductId = 1 AND Quantity = 10;
DECLARE @Changed int = @@ROWCOUNT;
IF @Changed <> 1
THROW 50001, 'Expected exactly one changed row.', 1;
ROLLBACK TRANSACTION;
END TRY
BEGIN CATCH
IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;
THROW;
END CATCH;
SELECT ProductId, Quantity FROM #Stock ORDER BY ProductId;
DROP TABLE #Stock;
The OUTPUT row shows product 1 changing from 10 to 12. The final SELECT shows 10 and 20 again because the transaction rolled back. Capture @@ROWCOUNT immediately after the statement because later statements can overwrite it.
Adapt the Pattern to Real Changes
Keep a narrow predicate, expected row count and error handling. A preview query by itself does not lock the data against concurrent changes. Where needed, use an appropriate concurrency token such as a rowversion and a reviewed transaction/isolation strategy. Keep transactions short rather than leaving locks open while someone inspects a screen.
Only replace the rehearsal's rollback with a commit as part of the intended approved change. OUTPUT can return rows even when a statement or transaction later rolls back, so it is evidence of attempted changes, not proof of durable completion.
When using UPDATE with a join, make the source match unambiguous for each target row. Several source matches supplying different new values are a design problem, not a reliable way to choose one arbitrarily.
Microsoft References
Author: Herman Schoenfeld