简体   繁体   English

事务是否必须在 SQL 服务器的存储过程中?

[英]Do transactions have to be in Stored Procedures in SQL Server?

I have a bunch of update and insert queries which I call from my C# code that need to be in a transaction.我有一堆更新和插入查询,我从我的 C# 代码中调用这些查询需要在事务中。 I'd prefer to keep them in C# rather than use Stored Procedures.我宁愿将它们保存在 C# 中,而不是使用存储过程。 I use SQLCommand.ExecuteNonQuery() to begin and commit the transaction.我使用 SQLCommand.ExecuteNonQuery() 开始并提交事务。 It works ok till I try commit the transaction, when I get a message that "The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION".在我尝试提交事务之前它工作正常,当我收到一条消息“COMMIT TRANSACTION 请求没有相应的 BEGIN TRANSACTION”时。 I am closing the connection between calls.我正在关闭通话之间的连接。 Is this the problem?这是问题吗?

No they don't.不,他们没有。

One can control the transaction in C# directly on the connection itself or use an ambient transaction using the System.Transactions namespace if you want the transaction to span across database connections or even different databases (Distributed Transaction).如果您希望事务跨越数据库连接甚至不同的数据库(分布式事务),可以直接在连接本身上控制 C# 中的事务,或者使用使用 System.Transactions 命名空间的环境事务。

If you are closing the connection between calls, use the System.Transactions namespace to control your transactions.如果您要关闭调用之间的连接,请使用 System.Transactions 命名空间来控制您的事务。 The transaction will then span across connections.然后,事务将跨越连接。

Some basic code to use the System.Transactions namespace:使用 System.Transactions 命名空间的一些基本代码:

using (TransactionScope scope = new TransactionScope())
{
     //Do operation 1 on connection 1 (open close connection)
     //Do operation 2 on connection 2 (open close connection)

     scope.Complete();
}

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

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