如何减少SQL Server死锁发生
死锁是指在某组资源中,两个或两个以上的线程在执行过程中,在争夺某一资源时而造成互相等待的现象,若无外力的作用下,它们都将无法推进下去,死时就可能会产生死锁,这些永远在互相等待的进程称为死锁线程。简单的说,进程A等待进程B释放他的资源,B又等待A
死锁是指在某组资源中,两个或两个以上的线程在执行过程中,在争夺某一资源时而造成互相等待的现象,若无外力的作用下,它们都将无法推进下去,死时就可能会产生死锁,这些永远在互相等待的进程称为死锁线程。简单的说,进程A等待进程B释放他的资源,B又等待A释放他的资源,这样互相等待就形成死锁。
如在数据库中,如果需要对一条数据进行修改,首先数据库管理系统会在上面加锁,以保证在同一时间只有一个事务能进行修改操作。如事务1的线程 T1具有表A上的排它锁,事务2的线程T2 具有表B上的排它锁,并且之后需要表A上的锁。事务2无法获得这一锁,因为事务1已拥有它。事务2被阻塞,等待事务1。然后,事务1需要表B的锁,但无法获得锁,因为事务2将它锁定了。事务在提交或回滚之前不能释放持有的锁。因为事务需要对方控制的锁才能继续操作,所以它们不能提交或回滚,这样数据库就会发生死锁了。
如在编写存储过程的时候,由于有些存储过程事务性的操作比较频繁,如果先锁住表A,再锁住表B,那么在所有的存储过程中都要按照这个顺序来锁定它们。如果无意中某个存储过程中先锁定表B,再锁定表A,这可能就会导致一个死锁。而且死锁一般是不太容易被发现的。
如果服务器上经常出现这种死锁情况,就会降低服务器的性能,所以应用程序在使用的时候,我们就需要对其进行跟踪,使用sp_who和sp_who2来确定可能是哪些用户阻塞了其他用户,,我们还可以用下面的存储过程来跟踪具体的死锁执行的影响:
create procedure sp_who_lock
as
begin
declare @spid int,@bl int,@intTransactionCountOnEntry
int,@intRowcount
int,@intCountProperties
int,@intCounter
int create table
#tmp_lock_who
(id int identity(1,1),spid smallint,bl smallint)IF @@ERROR0 RETURN
@@ERRORinsert into
#tmp_lock_who(spid,bl) select
0 ,blockedfrom (select * from sysprocesses where
blocked>0 )
a where not exists(select * from (select * from sysprocesses where blocked>0 )
b where a.blocked=spid)union select spid,blocked from sysprocesses where
blocked>0IF
@@ERROR0 RETURN @@ERROR -- 找到临时表的记录数select
@intCountProperties = Count(*),@intCounter = 1from #tmp_lock_whoIF
@@ERROR0 RETURN @@ERROR if @intCountProperties=0select
'现在没有阻塞和死锁信息'
as message-- 循环开始while @intCounter
@spid = spid,@bl = blfrom #tmp_lock_who where id = @intCounter beginif @spid =0 select
'引起数据库死锁的是: '+ CAST(@bl AS VARCHAR(10)) + '进程号,
其执行的SQL语法如下'elseselect
'进程号SPID:'+ CAST(@spid AS VARCHAR(10))+ '被' +
'进程号SPID:'+ CAST(@bl AS VARCHAR(10)) +'阻塞,
当前进程执行的SQL语法如下'DBCC INPUTBUFFER (@bl )end --
循环指针下移set @intCounter = @intCounter + 1enddrop table #tmp_lock_who
return 0
我们只需要通过在查询分析器里面执行sp_who_lock,就可以具体捕捉到执行的堵塞进程,这时我们就可以对对应的SQL语句或者存储过程进行性能上面的改进及设计。
所以我们在数据库设计的时候,虽然不能完全避免死锁,但可以使死锁的数量尽量减少。增加事务的吞吐量并减少系统开销,因为只有很少的事务,所以就得遵循下面的原则:
按同一顺序访问对象
如果所有并发事务按同一顺序访问对象,则发生死锁的可能性会降低。在写SQL语句或存储过程的时候,就需要按照顺序在两个并发事务中先获得表A上的锁,然后获得表B上的锁,当第一个事务完成之前,另一个事务被阻塞在表A上。第一个事务提交或回滚后,第二个事务继续进行,而不能在语句里面写先获得表B上的锁,然后再获得表A的锁。
避免事务中的用户交互
避免编写包含用户交互的事务,因为运行没有用户交互的批处理的速度要远远快于用户手动响应查询的速度,例如答复应用程序请求参数的提示。例如,如果事务正在等待用户输入,而用户就去做别的事了,则用户将此事务挂起使之不能完成。这样将降低系统的吞吐量,因为事务持有的任何锁只有在事务提交或回滚时才会释放。即使不出现死锁的情况,访问同一资源的其它事务也会被阻塞,等待该事务完成。
保持事务简短并在一个批处理中
在同一数据库中并发执行多个需要长时间运行的事务时通常发生死锁。事务运行时间越长,其持有排它锁或更新锁的时间也就越长,从而堵塞了其它活动并可能导致死锁。保持事务在一个批处理中,可以最小化事务的网络通信往返量,减少完成事务可能的延迟并释放锁。
使用低隔离级别
确定事务是否能在更低的隔离级别上运行。执行提交读允许事务读取另一个事务已读取(未修改)的数据,而不必等待第一个事务完成。使用较低的隔离级别(例如提交读)而不使用较高的隔离级别(例如可串行读)可以缩短持有共享锁的时间,从而降低了锁定争夺。
使用绑定连接
使用绑定连接使同一应用程序所打开的两个或多个连接可以相互合作。次级连接所获得的任何锁可以象由主连接获得的锁那样持有,反之亦然,因此不会相互阻塞。
下面有一些对死锁发生的一些建议:
1)对于频繁使用的表使用集簇化的索引;
2)设法避免一次性影响大量记录的T-SQL语句,特别是INSERT和UPDATE语句;
3)设法让UPDATE和DELETE语句使用索引;
4)使用嵌套事务时,避免提交和回退冲突;
5)对一些数据不需要及时读取更新值的表在写SQL的时候在表后台加上(nolock),如:Select * from tableA(nolock)

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

WindowsServerBackup is a function that comes with the WindowsServer operating system, designed to help users protect important data and system configurations, and provide complete backup and recovery solutions for small, medium and enterprise-level enterprises. Only users running Server2022 and higher can use this feature. In this article, we will explain how to install, uninstall or reset WindowsServerBackup. How to Reset Windows Server Backup If you are experiencing problems with your server backup, the backup is taking too long, or you are unable to access stored files, then you may consider resetting your Windows Server backup settings. To reset Windows

How to reduce memory usage through PHP functions. In development, memory usage is a very important consideration. If a large amount of memory is used in a program, it may cause slowdowns or even program crashes. Therefore, reasonably managing and reducing memory usage is an issue that every PHP developer should pay attention to. This article will introduce some methods to reduce memory usage through PHP functions, and provide specific code examples for readers' reference. Use the unset() function to release variables in PHP. When a variable is no longer needed, use

On the occasion of releasing the build 26040 version of Windows Server, Microsoft announced the official name of the product: Windows Server 2025. Also launched is the Windows11WindowsInsiderCanaryChannel version build26040. Some friends may still remember that many years ago someone successfully converted Windows NT from workstation mode to server mode, showing the commonalities between various versions of Microsoft operating systems. Although there are clear differences between Microsoft's current version of the server operating system and Windows 11, those who pay attention to the details may be curious: why Windows Server updated the brand,

How to modify the default name of nginx, you can disguise it a little, or you can install Tip: Generally, modifications are made before nginx is compiled. After modification, the code needs to be recompiled as follows: scr/core/nginx.conf#definenginx_version"1.4.7"#definenginx_ver"nginx/"n

How to deal with deadlock problems in C++ development Deadlock is one of the common problems in multi-threaded programming, especially when developing in C++. Deadlock problems may occur when multiple threads wait for each other's resources. If not handled in time, deadlock will not only cause the program to freeze, but also affect the performance and stability of the system. Therefore, it is very important to learn how to deal with deadlock problems in C++ development. 1. Understand the causes of deadlocks. To solve the deadlock problem, you first need to understand the causes of deadlocks. Deadlock usually occurs when

While Microsoft released the Win11 preview update for the desktop, today it also released the Windows Server Long Term Service Channel (LTSC) preview Build 25335. As usual, Microsoft did not publish a complete change log, or even provide a corresponding blog post. Microsoft has adjusted the Windows Server preview version update log to make it the same as the Canary channel version. If no new content is introduced, the official blog post will not be posted. Note from IT Home: The server brand has not been updated and is still Windows Server 2022 in the preview version. In addition, Microsoft calls these versions Windows Server vNext instead of the Windows version that is already on the market.

Multi-thread deadlock prevention mechanism includes: 1. Lock sequence; 2. Test and set up. The detection mechanism includes: 1. Timeout; 2. Deadlock detector. The article takes an example of a shared bank account and avoids deadlock through lock sequence. The transfer function first requests the lock of the transfer out account and then the transfer in account.

Deadlock and starvation in Go: Preventing and solving deadlock: Coroutines are waiting for each other and cannot perform operations. Use the runtime.SetBlockProfileRate function to detect. Prevent deadlocks: Use fine-grained locking, timeouts, and lock-free data structures to prevent deadlocks. Starvation: The coroutine continues to be unable to obtain resources, and fair locks are used to prevent starvation. Fair lock practice: Create a fair lock and wait for the coroutine to try to acquire the lock for the longest time to acquire the lock first.
