C#嵌套事务

C#嵌套事务,c#,sql-server,C#,Sql Server,我对下面显示的代码有一个问题 try { using (TransactionScope outerTransScope = new TransactionScope(TransactionScopeOption.RequiresNew)) { // 1.Change values in certain columns from the SQL database table using (TransactionScope innerT

我对下面显示的代码有一个问题

try
{
     using (TransactionScope outerTransScope = new TransactionScope(TransactionScopeOption.RequiresNew))
     {
          // 1.Change values in certain columns from the SQL database table

          using (TransactionScope innerTransScope = new TransactionScope(TransactionScopeOption.RequiresNew))
          {
               // 2.Update a column from the SQL database table by using the changed values from the outerTransScope as a JOIN condition.

               // 3.Commit the update query
               innerTransScope.Complete();
          }
     }
     // 4.Rollback the changed values that were executed in the outerTransScope
}
catch (Exception)
{
// Log the exception
}
我说这不会像我预期的那样起作用,对吗?因为outerTransScope实际上正在回滚innerTransScope,因为我从不提交outerTransScope

这意味着您只能在最后提交根事务时提交嵌套事务。如果未提交根事务,则即使提交了内部事务,也会回滚所有嵌套事务

是否有可能获得上面代码中显示的功能?提前谢谢

编辑: 假设我们有两张桌子,A桌和B桌

Table A:                         Table B:
Column A | Column B              Column A | Column B
Siemens  | 100                   SIE      | null
Siemens  | 101                   SIE      | null
Siemens  | 102                   SIE      | null
Siemens  | 103                   SIE      | null
我想用表A中的列B更新表B中的列B,但是我只想在表A中的列A和表B中的列A是100%匹配时执行此操作。现在什么也不会发生,因为表A中的A列不等于表B中的A列

因此,为了解决这个问题,用户可以使用我称之为actionscheme的东西编辑列。此actionscheme将用表A中的“SIE”替换“Siemens”。替换后,表A中的A列等于表B中的A列。通过此匹配,我现在可以用表A中B列的值更新表B中的B列。此更新完成后,我希望提交这些更改,并从中回滚我对A列所做的编辑表A(“西门子”变为“SIE”必须回滚)

在我的代码中,它看起来像这样:

try
{
    using (TransactionScope outerTransScope = new TransactionScope(TransactionScopeOption.RequiresNew))
    {
          // 1.Change Siemens into SIE Column A from Table A
              using (TransactionScope innerTransScope = new TransactionScope(TransactionScopeOption.RequiresNew))

          {
               // 2.Update Column B from Table B with the values of Column B from Table B, but only if Column A from Table A equals Column A from Table B. 

               // 3.Commit the update of Column B from Table B
               innerTransScope.Complete();
          }
     }
     // 4.Rollback the changes in Column A from Table A (So SIE becomes Siemens again).
}
catch (Exception)
{
// Log the exception
}

在嵌套事务中,没有事务层次结构。它将始终只有一个交易。您只能使用
TransactionScopeOption创建事务的依赖关系。此选项是必需的
,它将使用现有的可用事务并加入它。您正在为某个目的创建依赖项。如果您不想要依赖关系,那么首先完成初始事务处理,然后创建新的作用域并完成它。

我可以按要求回答这个问题,但这只是一个坏主意。您在这里尝试执行的操作将遇到许多问题,例如事务之间的隔离和事务之间的分布式死锁。SQL Server无法解决分布式死锁。通过30秒超时解决这些问题

这是一个脆弱的计划


找到一种不需要回滚任何内容的方法。例如,在临时表中创建临时数据并使用它。使用一个事务和一个连接。

当您出于测试目的运行此程序时(我假设您这样做了);您发现了什么?无法通过ADO.NET和SQL Server 2005+创建嵌套事务:请参阅事务语句应该是数据库中的存储过程,而不是客户端。如果创建存储过程来处理此事务,您将具有更好的灵活性。TransactionScopeOption.RequiresNew会使内部事务独立于外部事务,因此将立即提交,而不是等待外部事务提交或回滚。但是,您对SqlServer的理解可能会因其支持的内容而异。您可能需要在内部事务中打开新的连接。