批处理结束时检测到未提交的事务。该事务已被回滚。

7

我有一个存储过程,用事务从c#代码中调用。当我在C#中运行代码(它是控制台应用程序)时,在catch块中没有得到结果,而是抛出了异常:

批处理结束时检测到不可提交的事务。事务被回滚。

C#代码:

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace app1
{
    class Program
    {
        static void Main(string[] args)
        {
            string res = "";
            string resDesc = "";

            res = WriteToDB(1,out resDesc);

            Console.WriteLine(res);
            Console.WriteLine(resDesc);


            Console.Read();
        }

        public static string WriteToDB(int val, out string resultDesc)
        {
            resultDesc = "";
            string result = "";
            string connectionString = ConfigurationManager.ConnectionStrings["SqlAppConnection"].ConnectionString;
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                SqlTransaction transaction = connection.BeginTransaction("transcation1");
                try
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.Connection = transaction.Connection;
                        cmd.Transaction = transaction;
                        cmd.CommandText = "usp_Test_Proc";
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@check", val);
                        SqlParameter res = cmd.Parameters.Add("@result", SqlDbType.Int);
                        res.Direction = ParameterDirection.Output;
                        SqlParameter resDesc = cmd.Parameters.Add("@resultDesc", SqlDbType.VarChar, 100);
                        resDesc.Direction = ParameterDirection.Output;
                        cmd.ExecuteNonQuery();
                        result = res.Value.ToString().Trim();
                        resultDesc = resDesc.Value.ToString();
                        transaction.Commit();
                    }
                }
                catch (Exception ex)
                {
                    result = "Exception";
                    resultDesc = ex.Message;
                    transaction.Rollback();
                }
            }
            return result;
        }

    }
}

存储过程:

ALTER PROCEDURE [dbo].[usp_Test_Proc] (
                                            @check        int, 
                                            @result           INT output, 
                                            @resultDesc       VARCHAR(100) 
output) 
AS 
  BEGIN 
      SET nocount ON; 
      SET xact_abort ON;             

      IF @check != 0 
        BEGIN 
            BEGIN try              
                SET @result = 0; 
                SET @resultDesc = 'aa'; 
                --RAISERROR('Error from raiserror',1,1)
                THROW 99001, 'Error from throw', 1;
            END try
            BEGIN catch 
                SET @result = 1; 
                SET @resultDesc = concat('catch block',ERROR_MESSAGE()); 
            END catch; 
        END 
        ELSE
        BEGIN
                SET @result = 0; 
                SET @resultDesc = 'done'; 
                end
  END; 

GO

当存储过程出现错误时,我没有进入catch块,而是收到了一个异常,上面写着“在批处理结束时检测到不可提交的事务。该事务已被回滚。” 但是如果我在SSMS中运行存储过程,它就像预期的那样工作: enter image description here 为什么从C#代码调用时结果不同?

我的存储过程里没有事务...是吗?默认情况下有吗?我的计划是在循环中调用存储过程...如果所有操作都成功,则从.NET代码提交事务,否则能够回滚... - psj01
1
抱歉,你是对的。你有一个TRY...CATCH。 - William Xifaras
2
请查看文档 https://learn.microsoft.com/en-us/sql/t-sql/language-elements/try-catch-transact-sql?view=sql-server-2017 中的“不可提交事务和XACT_STATE”部分。 - William Xifaras
1
@psj01:我现在看到你也在客户端启动事务,但我建议不要这样做。相反,只在存储过程内开始事务。然而,在客户端的Catch块中,如果存储过程超时并且从未到达catch块,则还应该有一个IF @@TRANCOUNT>0 ROLLBACK(需要)。 - Razvan Socol
@RazvanSocol 我在客户端使用事务的原因是想要在循环内部调用这个存储过程并插入一些记录,如果其中任何一个失败,我希望回滚整个操作。 - psj01
显示剩余10条评论
1个回答

2
这是因为你设置了 'set xact_abort on'。根据文档,xact_abort用于“指定是否在Transact-SQL语句引发运行时错误时自动回滚当前事务”。此外,你需要在throw中将'state'值设置为-1,以使事务无法提交。

我的存储过程没有引发或抛出任何错误,但我仍然收到“在批处理结束时检测到不可提交的事务。事务已回滚。”的错误提示。在SSMS下运行正常。 - Sam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接