Question

Identify the output for the following Code

PRINT 'Before Transaction'
SELECT @@TRANCOUNT
BEGIN TRAN T1
PRINT 'After transaction T1 starts'
/* Value of @@TranCount is 1 */
SELECT @@TRANCOUNT
BEGIN TRAN T2 save TRAN T2
--save tran T2
PRINT 'After transaction T2 starts'
/* Value of @@TranCount is 2 */
SELECT @@TRANCOUNT
ROLLBACK TRAN T2
PRINT 'After transaction T2 roll backs'
/* Value of @@TranCount is still 2 as the rollback failed due to a error */
SELECT @@TRANCOUNT ---------[IT SHOUD BE 1,BUT WHY RESULT IS COMING AS 2?]
ROLLBACK TRAN T1
PRINT 'After transaction T1 roll backs'
/* Value of @@TranCount is 0 */
SELECT @@TRANCOUNT

What will be the reason for the improper Output ?

Was it helpful?

Solution

Answer lies in your code, as you have used save TRAN T2, Transaction T2 get saved and rollback doesn't affect @@TRANCOUNT value

Try to run below query multiple times in SQL Server....you will see value of @@TRANCOUNT gets increased by 1, every time you execute this query.

SELECT @@TRANCOUNT
BEGIN TRAN T2 save TRAN T2
PRINT 'After transaction T2 starts'
SELECT @@TRANCOUNT
ROLLBACK TRAN T2
PRINT 'After transaction T2 roll backs'
SELECT @@TRANCOUNT

OTHER TIPS

From MSDN

ROLLBACK TRANSACTION decrements @@TRANCOUNT to 0, except for ROLLBACK TRANSACTION savepoint_name, which does not affect @@TRANCOUNT.

You have transaction T2 save so ROLLBACK has no effect on @@TRANCOUNT.

If you use ROLLBACK on transaction T1 , @@Trancount will be reset to ZERO

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top