0

I encountered an error while trying to execute the query below.

if exists (select null from sys.sysobjects where type='P' and name = 'myProc')
    drop PROCEDURE myProc
go

create procedure myProc
as
begin
    set nocount on
    set xact_abort on

    begin try
        declare @trancount int = @@trancount

        if @trancount = 0
            begin tran
        else
            save tran MySave

        raiserror ('123213123',16,1)

        if @trancount = 0
            commit
    end try 
    begin catch
        if @trancount = 0
            rollback
        else
            if XACT_STATE() = 1
                rollback tran MySave
            else
                rollback    
    end catch
end
go

begin tran
    EXEC myProc

if @@TRANCOUNT >0
    rollback

the error is

Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0.

I've read many topics about similar problems but can't get it clear so far what's the reason in my case. Could anyone explain me why I get it and what should I do to avoid it. Thanks in advance

upd. I can simplify the code of MyProc like

create procedure myProc
as
begin
    set nocount on
    set xact_abort on

    begin try
        begin tran
           raiserror ('123213123',16,1)
        commit
    end try 
    begin catch
        rollback
    end catch
end
go

It doesn't solve my problems. the same error occurs

0

1 Answer 1

0

Try this:

ALTER PROCEDURE myProc
AS
    BEGIN
        SET NOCOUNT ON
        SET XACT_ABORT ON

        BEGIN TRY
            DECLARE @trancount INT = @@trancount

            IF @trancount = 0
                BEGIN TRAN
            ELSE
                SAVE TRAN MySave

            RAISERROR ('123213123',16,1)

            IF @trancount = 0
                COMMIT
        END TRY 
        BEGIN CATCH
            IF XACT_STATE() <> 0
                AND @trancount = 0
                ROLLBACK TRANSACTION;
        END CATCH
    END
GO

BEGIN TRAN
EXEC myProc


IF @@TRANCOUNT > 0
    ROLLBACK
Sign up to request clarification or add additional context in comments.

3 Comments

trancount is a count of transaction before MyProc is processing. if trancount equals 0, I start a trancaction (begin tran) and then, if error occurs, rollback it, if @trancount >0 it means I already inside an outer transaction. so I make a save point
@ Giorgi Nakeuri, yes it works. but I'm feeling it's not what I really wanted to get and before we resume, could you (or anybode else) think me up an example when i get into catch-block with XACT_STATE() = 1
@zagrr, comment line --SET XACT_ABORT ON

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.