这个TRANSACTION对我来说是ROLLBACK(ed)吗?

时间:2013-10-21 11:10:59

标签: c# sql-server transactions sqltransaction

如果我通过尝试创建现有表而导致错误,则现有事务似乎已经自行回滚:

private void CreateSomeThings()
{
    SqlConnection SqlConn = new SqlConnection(ConnectionString);
    SqlConn.Open();

    (new SqlCommand("BEGIN TRANSACTION", SqlConn)).ExecuteNonQuery();

    try
    {
        (new SqlCommand("CREATE TABLE sometable ([some_id] [int] IDENTITY(1,1) NOT NULL)", SqlConn)).ExecuteNonQuery();

        // Create the table again, but carry on by catching the exception
        try
        {
            (new SqlCommand("CREATE TABLE sometable ([some_id] [int] IDENTITY(1,1) NOT NULL)", SqlConn)).ExecuteNonQuery();
        }
        catch (Exception)
        {
        }

        // If another exception is thrown
        (new SqlCommand("bingy bongy boo", SqlConn)).ExecuteNonQuery();

        (new SqlCommand("COMMIT TRANSACTION", SqlConn)).ExecuteNonQuery();
    }
    catch (Exception Ex)
    {
        try
        {
            // ... then this command will fail with "no corresponding BEGIN TRANSACTION"
            (new SqlCommand("ROLLBACK TRANSACTION", SqlConn)).ExecuteNonQuery();
        }
        catch (Exception Ex2)
        {
            throw;
        }
    }
}

我想了解发生了什么以及为什么。我希望事务回滚是我的责任 - 其他错误它不会这样做:例如,如果我只是调用“bingy bongy”,那么只有调用抛出一个异常,然后我在异常中ROLLBACK没有任何异常的问题。

2 个答案:

答案 0 :(得分:3)

SQL Server可以单方面决定回滚您的事务。这是SQL Server中的严重设计缺陷,因为您的应用程序永远无法知道事务是否仍处于活动状态。没有很好地记录什么类型的错误回滚以及哪种错误没有。例如,我想我记得唯一的密钥违规和其他数据错误不会回滚。但其他人呢。有些错误甚至会终止连接(这很少见,也不是设计缺陷)。

我建议您以第一个错误中止事务的方式进行编码,然后失败或重试所有内容。这可以为您节省很多麻烦。希望每批执行一个语句,否则您可能会冒险在事务之外运行第二个语句。

如果你真的想继续犯错,你必须做两件事:

  1. 构建不回滚的错误白名单。在那种情况下,你可以坚持下去。
  2. 检查SELECT @@TRANCOUNT交易是否仍然有效。

答案 1 :(得分:0)

您需要将事务对象传递给您正在使用的每个命令,以使它们参与同一事务。

通常的模式是:

using (var conn = new SqlConnection("your connection string here"))
{
    SqlTransaction trans = null;
    try
    {
        conn.Open();
        trans = conn.BeginTransaction();

        using (SqlCommand command = new SqlCommand("command text here", conn, trans))
        {
            // do your job
        }
        trans.Commit();
    }
    catch (Exception ex)
    {
        try
        {
            // Attempt to roll back the transaction.
            if (trans != null) trans.Rollback();
        }
        catch (Exception exRollback)
        {
            // Throws an InvalidOperationException if the connection  
            // is closed or the transaction has already been rolled  
            // back on the server.
        }
    }
}