A transaction in SQL Server is a logical unit of work that contains one or more SQL operations (such as INSERT, UPDATE, DELETE, or SELECT) that should be executed as a single unit. A transaction ensures that either all operations are successful or none are applied, maintaining the consistency of the database.
Transactions are used to ensure the ACID properties:-
Without transactions, individual queries might leave the database in an inconsistent state if one part of the operation fails.
Let’s say you have a bank account transfer operation where you want to transfer money from Account A to Account B. Here’s an example of how you might attempt it without a transaction:
-- Step 1: Debit from Account A
UPDATE Accounts
SET Balance = Balance - 100
WHERE AccountID = 1;
-- Step 2: Credit to Account B
UPDATE Accounts
SET Balance = Balance + 100
WHERE AccountID = 2;
Potential issues with above Query
Now let’s perform the same operation, but with transactions to ensure that both updates succeed together or fail together.
BEGIN TRANSACTION;
-- Step 1: Debit from Account A
UPDATE Accounts
SET Balance = Balance - 100
WHERE AccountID = 1;
-- Step 2: Credit to Account B
UPDATE Accounts
SET Balance = Balance + 100
WHERE AccountID = 2;
-- If both steps are successful, commit the transaction
COMMIT TRANSACTION;
What happens with the transaction:
In case of failure, we can handle it like this:
BEGIN TRY
BEGIN TRANSACTION;
-- Step 1: Debit from Account A
UPDATE Accounts
SET Balance = Balance - 100
WHERE AccountID = 1;
-- Step 2: Credit to Account B
UPDATE Accounts
SET Balance = Balance + 100
WHERE AccountID = 2;
-- If both steps are successful, commit the transaction
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
-- If an error occurs, rollback the transaction
ROLLBACK TRANSACTION;
-- You can also capture the error here and log it
PRINT ERROR_MESSAGE();
END CATCH;