My name is Kenneth Fisher and I am Senior DBA for a large (multi-national) insurance company. I have been working with databases for over 20 years starting with Clarion and Foxpro. I’ve been working with SQL Server for 12 years but have only really started “studying” the subject for the last 3. I don’t have any real "specialities" but I enjoy trouble shooting and teaching. Thus far I’ve earned by MCITP Database Administrator 2008, MCTS Database Administrator 2005, and MCTS Database Developer 2008. I’m currently studying for my MCITP Database Developer 2008 and should start in on the 2012 exams next year. My blog is at www.sqlstudies.com.

Transactions are great and wonderful things. They make sure that our work stays atomic, consistent, isolated and durable (yes ACID). And if we use an explicit transaction (created by BEGIN TRANSACTION) and we make a mistake we can always roll the transaction back. Unfortunately rolling back a transaction and committing a transaction aren’t quite the same.

Transactions can be nested. We can tell how many layers of transactions deep we are by looking at @@TRANCOUNT. When we create an explicit transaction it increases @@TRANCOUNT by 1. When we commit a transaction it decreases @@TRANCOUNT by 1. However when we roll back a transaction it decreases @@TRANCOUNT to 0. This means no matter how deep in nested transactions we are one ROLLBACK will undo the whole thing all the way back to the top. Easy to say but in order to help it sink in how about an example or two?

-- Create a table to use during the tests
CREATE TABLE tb_TransactionTest (value int)
GO

This demonstrates committing an “inner” transaction then rolling back the “outer”. Even though the “inner” transaction is committed when the “outer” one is rolled back the whole thing gets rolled back and no rows are in the table.

After rolling back the inner transaction we actually get an error when trying to commit the outer transaction. Logically it might seem like you could roll back the inner transaction and commit the remainder of the transaction however it doesn’t work that way. Once the ROLLBACK command is executed the whole transaction is rolled back all the way to the beginning. The last insert statement (value 3) is in an implicit transaction and will commit even though the COMMIT statement returns an error. So we end up with one row with a 3 in it.

One way to avoid the error is to take advantage of the @@TRANCOUNT system variable.

Transactions are a big subject which I’m going to explore over several posts. I am by no means going to cover the subject exhaustively but if you have any subjects you would like me to cover or think I’ve missed something feel free to comment or email me.