- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我在代码的不同位置遇到了以下问题。在调用存储过程后,从 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/
我在代码的不同位置遇到了以下问题。在调用存储过程后,从 DB (SQL Server) 返回一个 SqlException 消息“在批处理结束时检测到不可提交的事务。事务被回滚”。存储过程结构遵循此示
我是一名优秀的程序员,十分优秀!