0

我在尝试执行下面的查询时遇到错误。

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

错误是

EXECUTE 之后的事务计数表明 BEGIN 和 COMMIT 语句的数量不匹配。先前计数 = 1,当前计数 = 0。

我已经阅读了许多关于类似问题的主题,但到目前为止还不清楚我的情况是什么原因。谁能解释我为什么会得到它以及我应该怎么做才能避免它。提前致谢

更新。我可以简化 MyProc 的代码,例如

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

它不能解决我的问题。发生同样的错误

4

1 回答 1

0

尝试这个:

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
于 2015-01-30T08:00:15.130 回答