ALTERNATIVE of @@TRANSCOUNT in SQL

Shashank Agarkhed 86 Reputation points
2021-08-03T13:53:13.503+00:00

Hi All,

SQL Server 2016 version
I am using procedure code with following format

BEGIN TRY

BEGIN TRANSACTION

   SQL INSERT STATEMENTS

COMMIT TRANSACTION

END TRY

BEGIN CATCH

IF @@trancount > 0 ROLLBACK TRANSACTION

END CATCH

My question is how to stop using @@trancount in procedure code? Any alternative for @@trancount ??

T.I.A

Developer technologies | Transact-SQL
0 comments No comments
{count} votes

Accepted answer
  1. Erland Sommarskog 121.9K Reputation points MVP Volunteer Moderator
    2021-08-03T18:46:06.64+00:00

    I agree with Tom, outlawing @@trancount is lunacy. But you can use this instead:

    IF xact_state() <> 0 ROLLBACK TRANSACTION
    

    But do not simply comment out @@trancount. You cannot do a ROLLBACK without checking for an open transaction. That transaction may already have been rolled back by an inner scope when you arrive in the CATCH handler.

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Tom Phillips 17,771 Reputation points
    2021-08-03T14:20:29.663+00:00

    Why do you want to not use @@trancount?

    0 comments No comments

  2. Shashank Agarkhed 86 Reputation points
    2021-08-03T14:24:02.753+00:00

    SQL Syntax not allowed as per directions so looking for alternatives.
    T.I.A


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.