我在尝试执行以下查询时遇到错误。
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。
我已经阅读了很多关于类似问题的主题,但到目前为止还不清楚我的理由是什么原因。 任何人都可以解释我为什么得到它,我该怎么做才能避免它。 提前致谢
UPD。我可以简化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
它没有解决我的问题。发生同样的错误
答案 0 :(得分: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