Question : Xact_state or @@ TranCount to handle nest transaction rollbacks

Hi all,

I have a Store proc which calls a recursive store proc which in turn might call a few others. All are updating different tables etc in the system and all start with a transaction. I have a try catch block around the code and roll back on errors.  The bug I was getting was ....

The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION.

SO after reading a bit more on transactions I now see that if a rollback is called on a nested transaction it rolls back to the other Transaction. When I catch the error I try to roll it back and throw the error on to the calling store proc. The calling procedure then tries a roll back but there is none. This I seem to understand and it now makes sense.

However (the question before I bore you all) I was looking at ways to handle this and dont know whether to use Xact_state or @@trancount to decide whether to roll back or not.

So in each Catch I was going to put some code like..

start stor proc
...delcare som stuff...
BEGIN TRY
    BEGIN TRANSACTION
...do some stuff
    COMMIT TRANS
END TRY
BEGIN CATCH
        -- only roll back if this is the outer tranaction
        IF (XACT_STATE() = -1) AND (@@TranCount = 1)
             ROLLBACK TRANS

         -- build an error string
         SELECT @errorMsg = OBJECT_NAME(@@PROCID) + ': '+  cast( XACT_STATE() as varchar(3))  + ' --  @@TranCount = ' + cast( @@TranCount as varchar(3))      
          --throw the error on
          RAISERROR (@errorMsg, @errorSev, @errorState)
   END CATCH
... end store proc

Do I need the XACT_STATE or just use the @@Trancount.  Also I noticed in the debugger in SQL 2008 that if I put a watch on the @@TranCount variable, the minute I entered the store proc it go incremented and not when I excuted the statement... Begin Transaction. The same when I called the roll back... it didnt decrement, only when leaving the store proc... any ideas or is this just the debugger or SQL Server knowing that it has a transaction to start anyway??

thanks M

Answer : Xact_state or @@ TranCount to handle nest transaction rollbacks

Random Solutions  
 
programming4us programming4us