I read this Stackoverflow question Nested stored procedures containing TRY CATCH ROLLBACK pattern?
I'm in need of clarification on Transaction template what gbn have answered. I couldn't comment and ask there.
CREATE PROCEDURE [Name]
AS
SET XACT_ABORT, NOCOUNT ON
DECLARE @starttrancount int
BEGIN TRY
SELECT @starttrancount = @@TRANCOUNT
IF @starttrancount = 0
BEGIN TRANSACTION
[...Perform work, call nested procedures...]
IF @starttrancount = 0
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF XACT_STATE() <> 0 AND @starttrancount = 0
ROLLBACK TRANSACTION
RAISERROR [rethrow caught error using @ErrorNumber, @ErrorMessage, etc]
END CATCH
GO
My Question is!
Why to use ?
SELECT @starttrancount = @@TRANCOUNT , rather than using @@TRANCOUNT directly??
and why to check this?
IF @starttrancount = 0 BEGIN TRANSACTION
IF @starttrancount = 0 COMMIT TRANSACTION
I'm new to transaction , explanation with example would be so helpfull. Thanks :)