In T-SQL your “transaction scope” is defined by the combination of BEGIN TRANSACTION, COMMIT (or ROLLBACK) and optional SAVEPOINTs plus error handling. Unlike .NET’s TransactionScope class, there’s no single T-SQL keyword that automatically scopes everything for you—you build it yourself:
SET XACT_ABORT ON; -- Optional but highly recommended:
-- any runtime error causes an automatic rollback
BEGIN TRY
BEGIN TRANSACTION;
-- 1) Your first operation
UPDATE dbo.Accounts
SET Balance = Balance - 100
WHERE AccountID = 42;
-- 2) Your second operation
UPDATE dbo.Accounts
SET Balance = Balance + 100
WHERE AccountID = 99;
-- … more statements …
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
-- Something went wrong: roll back & report
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
DECLARE
@ErrorNumber INT = ERROR_NUMBER(),
@ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE();
-- Bubble up or log
RAISERROR('Transaction failed: %d – %s',
16, 1,
@ErrorNumber, @ErrorMessage);
END CATCH;
Key points
- SET XACT_ABORT ON
• Forces a rollback on most runtime errors (divide‐by‐zero, deadlock, etc.)
- BEGIN TRAN / COMMIT / ROLLBACK
• All DML/DDL between BEGIN and COMMIT is atomic.
- Nested transactions & SAVEPOINT
• You can “nest” but SQL Server really only tracks one commit/rollback level.
• Use SAVE TRANSACTION savepoint_name; and ROLLBACK TRANSACTION savepoint_name; for partial rollbacks.
Example with SAVEPOINT:
BEGIN TRY
BEGIN TRANSACTION;
-- do step A
SAVE TRANSACTION spA;
-- might fail…
IF @someCondition = 0
THROW 51000, 'Step A failed', 1;
-- do step B
SAVE TRANSACTION spB;
-- might fail…
IF @otherCondition = 0
THROW 52000, 'Step B failed', 1;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
-- Roll back only to the last savepoint if desired:
ROLLBACK TRANSACTION spA; -- all the work after spA is undone
-- handle/log…
END CATCH;
When to use a .NET TransactionScope?
• If your business logic spans multiple calls to SQL Server (or multiple resource managers), you can wrap your ADO.NET calls in a C# TransactionScope:
using(var scope = new TransactionScope())
using(var conn = new SqlConnection(connString))
{
conn.Open();
// All commands here enlist in the ambient transaction
new SqlCommand("…", conn).ExecuteNonQuery();
// …
scope.Complete(); // commit
}
But purely in T-SQL, stick to the pattern shown above.