Roll back the whole unit of work on error
Put related changes in one transaction and use TRY/CATCH to undo partial work when a required row is missing.
What you are trying to do
A transfer debits one local account, then checks that the destination exists. A missing destination raises a deliberate error and the debit must be rolled back.
Work through it
- Confirm that both accounts live in a local temporary table.
- Trace the debit inside BEGIN TRANSACTION.
- Read the @@ROWCOUNT check immediately after the destination update. THROW raises error 50001 when no destination row changed.
- Follow XACT_STATE and ROLLBACK in CATCH, then compare the final balances with the starting balances.
- The transaction changes temporary lab data only.
Check your work
The CATCH result reports ErrorNumber 50001 and the message Destination account not found. The final rows remain account 1 with 100 and account 2 with 50, proving the debit was rolled back.
Practice SQL
Open in SQL FlowCREATE TABLE #Account (AccountId int NOT NULL PRIMARY KEY, Balance int NOT NULL);
INSERT INTO #Account (AccountId, Balance) VALUES (1, 100), (2, 50);
BEGIN TRY
BEGIN TRANSACTION;
UPDATE #Account SET Balance = Balance - 30 WHERE AccountId = 1;
UPDATE #Account SET Balance = Balance + 30 WHERE AccountId = 99;
IF @@ROWCOUNT <> 1
THROW 50001, 'Destination account not found.', 1;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF XACT_STATE() <> 0
ROLLBACK TRANSACTION;
SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
SELECT AccountId, Balance FROM #Account ORDER BY AccountId;
DROP TABLE #Account;
Knowledge check
Commands in this lesson
Next lesson Call a reusable module with a bound parameter