简体   繁体   English

asp.net中的事务与存储过程之间是否有任何区别

[英]Is there any difference between transactions in asp.net and stored procedure

If I have 3 sql queries and all three must be executed or none. 如果我有3个sql查询,并且所有三个都必须执行或不执行。 Is there any difference if I write this query in asp.net code or stored procedure? 如果我用asp.net代码或存储过程编写此查询,会有什么区别?

If you are doing everything for current connection on one DB instance basically you will see no difference to use T-SQL transactions (BEGIN TRAN/COMMIT TRAN) or ADO.NET transactions(TransactionScope, BeginTransaction...) 如果基本上在一个数据库实例上完成当前连接的所有操作,则使用T-SQL事务(BEGIN TRAN / COMMIT TRAN)或ADO.NET事务(TransactionScope,BeginTransaction ...)不会有任何区别。

But note that you can group multiple connections (requests to several DB instances) in one transaction using transaction scope. 但是请注意,您可以使用事务作用域在一个事务中对多个连接(对多个数据库实例的请求)进行分组。

Both are valid ways for managine transactions. 两者都是进行常规交易的有效方法。 Using a stored procedure has the advantage of less network traffic, probably faster execution, better encapsulation of the database stuff etc, while using asp.net allows you to involve some high-level logic or using parts of your other programming which may influence what your queries do. 使用存储过程的优点是更少的网络流量,可能更快的执行,更好的数据库内容封装等,而使用asp.net则可以使您包含一些高级逻辑或使用其他程序的一部分,这可能会影响您的内容。查询。

You can use the TransctionScope in .NET in the same way as you would use a transaction in the database. 您可以以与在数据库中使用事务相同的方式在.NET中使用TransctionScope

Be careful to choose the right isolation level though. 但是请小心选择正确的隔离级别

By default, TransactionScope executes with the Serializable isolation level. 默认情况下, TransactionScope以可序列化隔离级别执行。 This is probably not what you want. 这可能不是您想要的。

The database default isolation level will more likely be Read committed. 数据库默认隔离级别将更有可能被提交为Read。

For efficiency reasons you'd better write a SP with a transaction that rolls back on error. 出于效率方面的考虑,您最好编写一个带有错误回滚的事务的SP。 If only for simplicity, direct SQL, and the fact that SP get kind of compiled once, for faster execution in the future. 如果只是为了简单起见,请直接执行SQL,并为SP一次性编译一次,以便将来更快地执行。

When using SqlConnection.BeginTransaction() there is no difference. 使用SqlConnection.BeginTransaction()时没有区别。

This question, though, is a possible duplicate of What's the difference between an SQL transaction at the stored procedure level and one at the SqlConnection level? 但是,此问题可能是重复的:存储过程级别的SQL事务与SqlConnection级别的SQL事务什么区别?

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

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