我在运行在 MS SQL Server 2005 之上的 .NET 2.0 web 应用程序上遇到了非常罕见但令人讨厌的 SQL 死锁.过去,我们一直以非常经验的方式处理 SQL 死锁 - 基本上是调整查询,直到它起作用了.
然而,我发现这种方法非常不令人满意:耗时且不可靠.我更愿意遵循确定性查询模式,以确保设计不会遇到 SQL 死锁 - 永远.
例如,在 C# 多线程编程中,一个简单的设计规则,例如必须按照它们的字典顺序获取锁,以确保不会永远发生死锁.>
是否有任何 SQL 编码模式可以保证防死锁?
编写防死锁代码真的很难.即使您以相同的顺序访问表,您仍然可能会遇到死锁 [1].我在我的博客上写了 一篇博文,其中详细阐述了一些方法,可以帮助您避免并解决死锁情况.
如果您想确保两个语句/事务永远不会死锁,您可以通过使用 sp_lock 系统存储过程观察每个语句消耗哪些锁来实现它.为此,您必须非常快,或者使用带有锁定提示的打开事务.
<小时>注意事项:
I am encountering very infrequent yet annoying SQL deadlocks on a .NET 2.0 webapp running on top of MS SQL Server 2005. In the past, we have been dealing with the SQL deadlocks in the very empirical way - basically tweaking the queries until it work.
Yet, I found this approach very unsatisfactory: time consuming and unreliable. I would highly prefer to follow deterministic query patterns that would ensure by design that no SQL deadlock will be encountered - ever.
For example, in C# multithreaded programming, a simple design rule such as the locks must be taken following their lexicographical order ensures that no deadlock will ever happen.
Are there any SQL coding patterns guaranteed to be deadlock-proof?
Writing deadlock-proof code is really hard. Even when you access the tables in the same order you may still get deadlocks [1]. I wrote a post on my blog that elaborates through some approaches that will help you avoid and resolve deadlock situations.
If you want to ensure two statements/transactions will never deadlock you may be able to achieve it by observing which locks each statement consumes using the sp_lock system stored procedure. To do this you have to either be very fast or use an open transaction with a holdlock hint.
Notes:
这篇关于零 SQL 死锁设计 - 任何编码模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!