SQL SERVER – Finding Open Transactions for Session – @@TRANCOUNT

To inspect Open Transactions for Session nesting on my connection, I use @@TRANCOUNT. It does not directly inspect another session.

Three nested frames surround one shared unfinished workpiece.

-- Run in a fresh session with no existing transaction.
IF @@TRANCOUNT <> 0 THROW 50000, 'Use a fresh session for this example.', 1;
BEGIN TRANSACTION;
BEGIN TRANSACTION;
BEGIN TRANSACTION;
COMMIT TRANSACTION;
SELECT @@TRANCOUNT AS NestingCount, XACT_STATE() AS TransactionState;
ROLLBACK TRANSACTION;
SELECT @@TRANCOUNT AS AfterCleanup;
Nested transaction count is 2 with XACT_STATE 1; after the demonstrated cleanup, the count is 0.
Nested transaction count is 2 with XACT_STATE 1; after the demonstrated cleanup, the count is 0.

The example begins three levels and commits once, returning 2. They belong to one transaction. An inner COMMIT reduces the count. It does not independently harden those changes.

The guard rejects a connection that already has a transaction. The final ROLLBACK cleans up the example and resets nesting. XACT_STATE answers a different question. It identifies absent, committable or uncommittable transaction state.

Inside a procedure, @@TRANCOUNT still describes the caller’s connection. That includes transactions opened earlier. Use permitted session and transaction DMVs for another session and correlate identifiers.

Reference: Transaction nesting count.

Related reading

Nested transaction count is not independent durability, it is nesting state within the current connection.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.


Discover more from SQL Authority with Pinal Dave

Subscribe to get the latest posts sent to your email.

SQL Scripts, SQL Server, SQL Stored Procedure, SQL Transactions
Previous Post
SQL SERVER – Simple Recovery Model and Restrictions
Next Post
SQL Agent Operators and Notifications: Who Gets the Alert

Related Posts

1 Comment. Leave new

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.