SQL Server › Transactions & ACID
How do you check whether a transaction is currently active and view its properties within a session?
IntermediateAnswer
You can use the @@TRANCOUNT system function to check how many transactions are currently active and nested within the current session, and the XACT_STATE function to determine whether the current transaction, if any, is in a normal, committable state or has become an uncommittable state due to an earlier error.
BEGIN TRANSACTION;
PRINT @@TRANCOUNT; -- shows 1
SELECT XACT_STATE(); -- shows 1 for a normal, committable transactionReal-world example A developer troubleshooting an unexpected error checks @@TRANCOUNT within their stored procedure to confirm exactly how many nested transactions are currently open, helping them understand and fix a mismatched BEGIN and COMMIT pairing.