如何取消/重置 SQL Server 的事务隔离级别?
也许我误解了有关事务或 SQL Server 正在做什么的事情,但请考虑以下 T-SQL:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
GO
BEGIN TRANSACTION
-- DO SOME READS AND OTHER THINGS
COMMIT
-- OK, WHAT HAPPENS TO THE ISOLATION LEVEL AFTER THIS?
也许这并不重要,但我喜欢那种温暖模糊的感觉,即我让事情保持原来的样子。完成我正在做的事情。是否可以将隔离级别重置回原始状态,无论之前的状态如何?
Maybe I'm misunderstanding something about transactions or what SQL Server is doing but consider the following T-SQL:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
GO
BEGIN TRANSACTION
-- DO SOME READS AND OTHER THINGS
COMMIT
-- OK, WHAT HAPPENS TO THE ISOLATION LEVEL AFTER THIS?
Maybe it doesn't matter, but I like the warm fuzzy feeling that I'm leaving things the way they were once I'm done doing what I'm doing. Is it possible to reset the isolation level back to the original state regardless of what the state was before?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您的代码在存储过程中执行,则更改仅适用于存储过程的范围内 - 当存储过程返回时,连接的隔离级别将自动恢复到之前的级别:(
忽略 sys.objects 的结果集,输出 2、4 和 2 作为隔离级别)。
If your code is executed inside a stored procedure, the change only applies during the scope of the stored proc - when the stored proc returns, the isolation level for the connection will automatically revert to it's previous level:
(Ignoring result set from sys.objects, this outputs 2, 4 and 2 as the isolation levels).
您可以通过
sys.dm_exec_sessions.transaction_isolation_level 了解当前级别
如果需要跨批次,请使用
SET CONTEXT_INFO
保留该值,稍后也可以从 sys.dm_exec_sessions 读取该值。You know the current level from
sys.dm_exec_sessions.transaction_isolation_level
If you need to span batches, then use
SET CONTEXT_INFO
to preserve the value which can also be read from sys.dm_exec_sessions later on.GBN 解决方案对我不起作用。我怀疑它在其他地方是否有效。
问题是返回到先前的隔离级别仅在 EXEC 上下文中有效。我的脚本如下。请注意,如果当前隔离包括快照,它也不会尝试更改隔离。 (如果你尝试,就会失败)。
GBNs solution does not work for me. I doubt it will work elsewhere.
The problem is that return to previous isolation level is only valid within the context of the EXEC. My script is below. Note, that it also does not attempt to change the isolation if current isolation includes snapshots. (It will fail if you try).