asp.net中的事务和存储过程有什么区别
如果我有 3 个 sql 查询,并且所有三个查询都必须执行或都不执行。如果我用 ASP.NET 代码或存储过程编写此查询有什么区别吗?
If I have 3 sql queries and all three must be executed or none. Is there any difference if I write this query in asp.net code or stored procedure?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您在一个数据库实例上为当前连接执行所有操作,基本上您将发现使用 T-SQL 事务(BEGIN TRAN/COMMIT TRAN)或 ADO.NET 事务(TransactionScope、BeginTransaction...)没有任何区别,
但请注意,您可以分组使用事务范围在一个事务中进行多个连接(对多个数据库实例的请求)。
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...)
But note that you can group multiple connections (requests to several DB instances) in one transaction using transaction scope.
两者都是管理交易的有效方法。使用存储过程的优点是网络流量更少,可能执行速度更快,数据库内容更好的封装等,而使用 ASP.NET 允许您涉及一些高级逻辑或使用其他编程的一部分,这可能会影响您的工作查询可以。
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.
您可以像在数据库中使用事务一样在 .NET 中使用
TransctionScope
。不过,请小心选择正确的隔离级别。
默认情况下,
TransactionScope
使用可序列化隔离级别执行。这可能不是您想要的。数据库默认隔离级别更有可能是已提交读。
You can use the
TransctionScope
in .NET in the same way as you would use a transaction in the database.Be careful to choose the right isolation level though.
By default,
TransactionScope
executes with the Serializable isolation level. This is probably not what you want.The database default isolation level will more likely be Read committed.
出于效率原因,您最好编写一个带有错误时回滚事务的 SP。如果只是为了简单起见,直接 SQL,并且 SP 只编译一次,以便将来更快地执行。
For efficiency reasons you'd better write a SP with a transaction that rolls back on error. If only for simplicity, direct SQL, and the fact that SP get kind of compiled once, for faster execution in the future.
使用
SqlConnection.BeginTransaction()
时没有区别。不过,这个问题可能与 存储过程级别的 SQL 事务和 SqlConnection 级别的 SQL 事务有什么区别?
When using
SqlConnection.BeginTransaction()
there is no difference.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?