【问题标题】:Unable to use same SQL Server table for multiple inserts and updates inside C# dbtransaction无法在 C# dbtransaction 中使用相同的 SQL Server 表进行多次插入和更新
【发布时间】:2016-04-08 07:12:47
【问题描述】:

在 C# dbtransaction 中使用单个 SQL Server 表进行多次插入和更新时出现问题。

以下是步骤:

  1. 在 try 块中启动事务。
  2. 我使用事务中的存储过程将一行插入到 SQL Server 表中,该事务返回插入的 ID
  3. 我必须更新上面插入行的列
  4. 如果成功则我必须提交,否则如果失败则在 catch 中回滚

问题是插入行后它不会更新,因为它会在更新时给出超时错误(因为我认为它在插入后锁定了一个表)。

插入后如何更新?

这是我的代码:

using (var transaction = cnctn.BeginTransaction())
{
      try 
      {
         var ID = InsertInEmployeeTable(Employee);   // inserted successfully
         var Status = UpdateInEmployeeTable(ID,"Description");   // here timeout error happens
         transaction.Commit();
      } 
      catch(SqlException sqlError) 
      {
         transaction.Rollback();
      }
}

【问题讨论】:

  • 如果没有来自两次插入和更新调用的代码,任何答案都只是一个疯狂的猜测

标签: c# asp.net sql-server


【解决方案1】:
using (var transaction = cnctn.BeginTransaction())
{
      try 
      {
         var ID = InsertInEmployeeTable(Employee); //inserted succesfully
     var Status = UpdateInEmployeeTable(ID,"Description"); //Here timeout error
         transaction.Commit();
      } 
      catch(SqlException sqlError) 
      {try
            {
                transaction.Rollback();
            }
            catch (Exception ex2)
            {
                // This catch block will handle any errors that may have occurred
                // on the server that would cause the rollback to fail, such as
                // a closed connection.
                Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
                Console.WriteLine("  Message: {0}", ex2.Message);
            }
      }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-16
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    相关资源
    最近更新 更多