INF: @@TRANCOUNT Global Variable Detects Rollback

Last reviewed: April 25, 1997
Article ID: Q68938

The information in this article applies to:
  • Microsoft SQL Server version 4.2 for OS/2
  • Microsoft SQL Server, version 4.2

SUMMARY

@@TRANCOUNT is a global variable that contains the number of currently active transactions for the current user connection. This global variable can be used in the middle of a BEGIN TRANSACTION ... COMMIT TRANSACTION group to determine when and if that transaction has been rolled back.

The @@TRANCOUNT variable is incremented each time a new transaction is started with a BEGIN TRANSACTION command. It is decremented when a COMMIT TRANSACTION command is executed, or when the transaction has been rolled back. This global variable can be accessed by using the SELECT @@TRANCOUNT command.

When using only one transaction, @@TRANCOUNT will be 0 (zero) before the transaction. After the BEGIN TRANSACTION command is executed, @@TRANCOUNT will be 1 (one). If the transaction is completed successfully, @@TRANCOUNT will remain 1 until a COMMIT TRANSACTION command is performed. After this, @@TRANCOUNT will again be 0. However, if an error is encountered that causes the entire transaction to be rolled back, @@TRANCOUNT will be set to 0. This will occur before the COMMIT TRANSACTION command is executed.

This is especially useful when executing each statement of the transaction separately. Some errors will cause the transaction to be rolled back, while others will not. When you receive an error message, a quick check of @@TRANCOUNT will tell you whether your current transaction is still valid, or if it has been automatically rolled back.

MORE INFORMATION

Please note that when writing a DB-Library (DB-Lib) program, @@TRANCOUNT is global to one dbproc. If one DB-Library program opens two dbprocs to access the same SQL Server, each dbproc will have its own local, independent @@TRANCOUNT variable.


Additional query words: Windows NT
Keywords : kbprg SSrvServer SSrvTrans
Version : 4.2 | 4.2
Platform : OS/2 WINDOWS


THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Last reviewed: April 25, 1997
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.