Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When it's necessary to check @@trancount > 0 in try catch block?

Tags:

Sometimes I saw the following code snippet. When is the if @@trancount > 0 necessary with begin try? Both of them? Or it's a safe way(best practice) to check it always in case it's rollback before the check?

begin tran begin try   ... just several lines of sql ...   if @@trancount > 0 commit tran end try begin catch   if @@trancount > 0 rollback tran end catch 
like image 874
ca9163d9 Avatar asked Dec 21 '12 02:12

ca9163d9


People also ask

What is use of @@ Trancount in SQL?

@@TRANCOUNT (Transact-SQL)Returns the number of BEGIN TRANSACTION statements that have occurred on the current connection.

Is it correct best practice to have the try catch block inside the transaction or should the transaction be inside the try block?

Option A is the correct choice. It is possible for all statements in a transaction to work and then the actual COMMIT to fail, so you keep the COMMIT inside your TRY block so that any failure of the COMMIT will be caught and you can gracefully handle this error and rollback.

How can show error message in catch block in SQL Server?

Retrieving Error Information In the scope of a CATCH block, the following system functions can be used to obtain information about the error that caused the CATCH block to be executed: ERROR_NUMBER() returns the number of the error. ERROR_SEVERITY() returns the severity. ERROR_STATE() returns the error state number.

What is Transcount?

Transcount is a cloud-based logistics management application that enables companies to digitise and automate their logistics business processes.


1 Answers

I can think of a few scenarios to consider when dealing with @@trancount:

  1. The current transaction was called from another stored procedure which had its own transaction
  2. The current transaction was called by some .NET code with its own transaction
  3. The current transaction is the only transaction

I believe Remus Rusanu's Exception handling and nested transactions handles all these possibilities.

like image 117
8kb Avatar answered Oct 14 '22 15:10

8kb