简体   繁体   English

如何使用ADO.NET和SQL Server启用嵌套事务?

[英]How do I enable nested transactions with ADO.NET and SQL Server?

I have similar question to how to check if you are in a transaction . 我有类似的问题来检查你是否在交易中 Instead of checking, how do I allow nested transactions? 而不是检查,我如何允许嵌套事务?

I am using Microsoft SQL Server Database with ADO.NET. 我正在使用Microsoft SQL Server数据库与ADO.NET。 I have seen examples using T-SQL and examples starting transactions using begin and using transaction names. 我已经看到了使用T-SQL的示例以及使用begin和使用事务名​​称启动事务的示例。 When calling connection.BeginTransaction, I call another function in the same connection, and it calls BeginTransaction again which gives me the exception: 当调用connection.BeginTransaction时,我在同一个连接中调用另一个函数,并再次调用BeginTransaction,这给了我异常:

SqlConnection does not support parallel transactions.

It appears many Microsoft variants allow this, but I can't figure out how to do it with my .mdf file. 似乎许多Microsoft变种允许这样做,但我无法弄清楚如何使用我的.mdf文件。

How do I allow nested transactions with a Microsoft SQL Server Database using C# and ADO.NET? 如何使用C#和ADO.NET允许嵌套事务与Microsoft SQL Server数据库?

SQL Server as a whole does not support nested transactions. SQL Server作为一个整体不支持嵌套事务。 In T-SQL you can issue a BEGIN TRAN inside an earlier BEGIN TRAN but this is just for convenience. 在T-SQL可以发出BEGIN TRAN较早内BEGIN TRAN但是这仅仅是为了方便。 It's only the outer transaction that counts. 这只是外部交易的重要性。 The .NET client for SQL Server ( SqlConnection ) does not even allow you to do that and throws this exception when you try. SQL Server的.NET客户端( SqlConnection )甚至不允许您这样做,并在您尝试时抛出此异常。

It is a common misconception that SQL Server supports nested transactions. SQL Server支持嵌套事务是一种常见的误解。 It does not. 它不是。 opening multiple transactions and then calling commit does absolutely nothing. 打开多个事务,然后调用commit绝对没有。 you can easily write some test SQL to try this yourself. 您可以轻松编写一些测试SQL来自己尝试。 The only option here to emulate a nested transaction is to use Savepoints. 这里模拟嵌套事务的唯一选择是使用Savepoints。

I should add that the only thing that matters is when @@TRAN_COUNT reaches zero is the point at which only the outer transaction will be committed. 我应该补充一点,唯一重要的是当@@ TRAN_COUNT达到零时,只有外部事务才会被提交。

SqlConnection conn = new SqlConnection(@"Data Source=test;Initial Catalog=test;User ID=usr;Password=pass");
conn.Open();
var com = conn.CreateCommand();

com.CommandText = "BEGIN TRANSACTION";
com.ExecuteNonQuery();
com.CommandText = "BEGIN TRANSACTION";
com.ExecuteNonQuery();
com.CommandText = "INSERT INTO testTable (ParamName,ParamValue) values ('test','test');";
com.ExecuteNonQuery();
com.CommandText = "COMMIT TRANSACTION";
com.ExecuteNonQuery();
com.CommandText = "ROlLBACK TRANSACTION";
com.ExecuteNonQuery();

com.CommandText = "SELECT COUNT(*) FROM testTable ";

MessageBox.Show(string.Format("Found {0} rows.", com.ExecuteScalar()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM