Wrap the statements in an explicit transaction so they succeed or fail as one unit (atomicity), and roll back if any statement fails. Recommended pattern (SQL Server) SET XACT_ABORT ON; -- any run-time error aborts and rolls back the whole transaction BEGIN TRY BEGIN TRANSACTION; UPDATE Accounts SET Balance = Balance - @Amount WHERE AccountId = @FromAccount AND Balance >= @Amount; IF @@ROWCOUNT = 0 THROW 50001, 'Insufficient funds or account not found.', 1; UPDATE Accounts SET Balance = Balance + @Amount WHERE AccountId = @ToAccount; INSERT INTO Transfers (FromAccount, ToAccount, Amount, CreatedAt) VALUES (@FromAccount, @ToAccount, @Amount, SYSUTCDATETIME()); COMMIT TRANSACTION; END TRY BEGIN CATCH IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION; THROW; -- rethrow the original error to the caller END CATCH; Why each part matters - BEGIN TRANSACTION ... COMMIT makes all statements one atomic unit: either all changes are saved or none. - TRY/CATCH catches errors; ROLLBACK undoes partial changes. - SET XACT_ABORT ON ensures that most run-time errors (including some that do not transfer control to CATCH, such as client timeouts or attention events) roll back the entire transaction, instead of leaving it open with partial work. - Checking @@ROWCOUNT enforces business rules: an UPDATE that affects zero rows is not an error by itself. - THROW rethrows the error so the application knows the operation failed. - Checking @@TRANCOUNT avoids errors when no transaction is open. From application code (.NET example) await using var tx = await connection.BeginTransactionAsync(ct); try { /* execute commands with the transaction */ await tx.CommitAsync(ct); } catch { await tx.RollbackAsync(ct); throw; } EF Core's SaveChanges already wraps all its changes in one transaction; use explicit transactions (Database.BeginTransactionAsync) when combining several SaveChanges calls or raw SQL. Additional considerations - Keep transactions short to reduce locking and blocking. - Choose an appropriate isolation level if concurrent transactions could interfere. - Distributed operations across databases or services cannot rely on a single local transaction; use patterns such as the outbox or sagas.
Ravindra Wadile · · 0 likes