gpt4 book ai didi

c# - 数据库上没有事务的 SQL 错误 "uncommittable transaction is detected at the end of batch"

转载 作者:太空狗 更新时间:2023-10-29 23:51:06 25 4
gpt4 key购买 nike

我在代码的不同位置遇到了以下问题。在调用存储过程后,从 DB (SQL Server) 返回一个 SqlException 消息“在批处理结束时检测到不可提交的事务。事务被回滚”。存储过程结构遵循此示例:

USE [EXAMPLE_DB]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp_ExampleStoredProcedure]
@Parameter INT, @AnotherParameter INT

AS
BEGIN
BEGIN TRY

SET NOCOUNT ON;


DECLARE @Variable INT;
DECLARE @AnotherVariable CHAR;
DECLARE @ErrMsg VARCHAR;

SET @ErrMsg = '';

/*Doing Some Stuff Here (Select, IF-THEN, etc...)

/* I call another stored procedure */
EXECUTE [dbo].[sp_SecondStoredProcedure]
@Param = 'Blabla'
,@Param2 = 'BlaBlaBla'


/*Here I handle some custom output parameters from second stored
procedure to handle errors */



/* Other stuff here */

END TRY

BEGIN CATCH
SET @CustomExitCode = 'XXXXX';
SET @ErrMsg = (SELECT ERROR_MESSAGE());
END CATCH;

END

如您所见,在存储过程中没有事务处理。我使用 TransactionScope 类处理事务代码端 (C#),调用事务范围内的各种存储过程,包括上面的那个(失败的那个)。

问题是:如果我没有事务 SQL 端,只有一个 try-catch block ,所有事务处理都在代码上执行,为什么 SQL 会谈论不可提交的事务?

我已经在网上搜索了很多关于Uncommittable Transaction错误的资料,但实际上到处都是SQL端的事务处理。

我希望我已经以可以理解的方式解释了这个问题。我显然可以提供任何进一步的信息。

非常感谢您的帮助!

干杯,加布里埃尔

最佳答案

将 TRY BLOCK 中的所有操作封装在一个事务中,让 sql server 为您处理它,而不是您在应用程序中处理它。在 Try block 中显式开始 TRAN 和 COMMIT Trans,如果在此事务期间出现任何错误,则将其回滚。

我会做类似......

ALTER PROCEDURE [dbo].[sp_ExampleStoredProcedure]
@Parameter INT, @AnotherParameter INT
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
DECLARE @Variable INT;
DECLARE @AnotherVariable CHAR;
DECLARE @ErrMsg VARCHAR;

SET @ErrMsg = '';
BEGIN TRANSACTION; --<-- Begin here

/*Doing Some Stuff Here (Select, IF-THEN, etc...)*/

/* I call another stored procedure */
EXECUTE [dbo].[sp_SecondStoredProcedure]
@Param = 'Blabla'
,@Param2 = 'BlaBlaBla'
/*Here I handle some custom output parameters from second stored
procedure to handle errors */

/* Other stuff here */
COMMIT TRANSACTION; --<-- Commit here if nothing gone wrong

END TRY

BEGIN CATCH
IF (@@TRANCOUNT > 0)
BEGIN
ROLLBACK TRANSACTION; --<-- Rollback if something went wrong
END

/*Other error logging here*/
SELECT @CustomExitCode = 'XXXXX', @ErrMsg = ERROR_MESSAGE();
END CATCH;

END

关于c# - 数据库上没有事务的 SQL 错误 "uncommittable transaction is detected at the end of batch",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23891859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com