If you’ve been working with T-SQL scripts for a while, you’ve likely encountered variables. These are essential for writing scripts that go beyond basic SELECT, INSERT, UPDATE, or DELETE statements.
Variables can serve multiple purposes: they can act as parameters passed into stored procedures, hold the results of one query to use in another, or even help debug scripts during testing (you do test your scripts before running them on real data, right?).
One particularly interesting aspect of variables is how they behave in transactions, often in ways we might not expect.
What happens to a variable during a commit?
Let’s use a simple T-SQL script to output two messages to the screen. We’ll wrap the second message inside a transaction and commit it.
DECLARE @Message VARCHAR(50)
SET @MyMessage = 'Hello there'
SELECT @Message
BEGIN TRANSACTION
SET @Message = 'I''m inside a transaction'
COMMIT TRANSACTION
SELECT @Message
If we look at the results below we can see the first message outputs as we would expect and so does the second. There’s nothing unusual going on here.
So what happens to a variable during a rollback?
Let’s alter our T-SQL script to output two different messages this time. Instead of committing we’ll wrap the second message inside a transaction with a rollback.
DECLARE @Message VARCHAR(50)
SET @Message = 'Watch out, there''s a rollback coming up!'
SELECT @Message
BEGIN TRANSACTION
SET @Message = 'Ha, rollbacks don''t bother me!'
ROLLBACK TRANSACTION
SELECT @Message
The value of the variable wasn’t affected by the rollback at all. This is because variables exist outside of transactions!
How is this useful?
Understanding that variables exist independently of transactions will enhance your T-SQL scripting skills, helping you avoid surprises caused by seemingly odd behavior.
This is especially useful when debugging scripts. If an error occurs within a transaction and it gets rolled back, it can be challenging to pinpoint the issue since any changes to the data are reverted. By using variables, particularly table variables, you can preserve useful information about what happened, making it easier to troubleshoot and debug scripts more efficiently.

Pingback: T-SQL Variables and Transactions – Curated SQL