如何使用 ADO.NET 和 SQL Server 启用嵌套事务?
我有类似的问题如何检查如果您正在进行交易。除了检查之外,如何允许嵌套事务?
我正在将 Microsoft SQL Server 数据库与 ADO.NET 结合使用。我见过使用 T-SQL 的示例以及使用 begin 和使用事务名称启动事务的示例。当调用connection.BeginTransaction时,我在同一连接中调用另一个函数,它再次调用BeginTransaction,这给了我一个例外:
SqlConnection does not support parallel transactions.
似乎许多微软变体都允许这样做,但我不知道如何使用我的.mdf文件来做到这一点。
如何使用 C# 和 ADO.NET 允许与 Microsoft 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. I have seen examples using T-SQL and examples starting transactions using begin and using transaction names. When calling connection.BeginTransaction, I call another function in the same connection, and it calls BeginTransaction again which gives me the exception:
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.
How do I allow nested transactions with a Microsoft SQL Server Database using C# and ADO.NET?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
SQL Server 整体上不支持嵌套事务。在 T-SQL 中,您可以在较早的
BEGIN TRAN
内发出BEGIN TRAN
,但这只是为了方便。只有外部交易才重要。 SQL Server 的 .NET 客户端 (SqlConnection
) 甚至不允许您这样做,并且在您尝试时会抛出此异常。SQL Server as a whole does not support nested transactions. In T-SQL you can issue a
BEGIN TRAN
inside an earlierBEGIN TRAN
but this is just for convenience. 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 支持嵌套事务是一个常见的误解。事实并非如此。打开多个事务然后调用 commit 绝对不会执行任何操作。您可以轻松地编写一些测试 SQL 来亲自尝试。这里模拟嵌套事务的唯一选择是使用保存点。
我应该补充一点,唯一重要的是当 @@TRAN_COUNT 达到零时,只有外部事务才会被提交。
It is a common misconception that SQL Server supports nested transactions. It does not. opening multiple transactions and then calling commit does absolutely nothing. you can easily write some test SQL to try this yourself. The only option here to emulate a nested transaction is to use 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.