一、进程分析
--首先,查看进程,查看否存在阻塞进程,blocked>0都是当前被阻塞的进程
SELECT * FROM sys.sysprocesses WHERE blocked >0 ORDER BY blocked;
--找到被阻塞的线程后,想要继续查看进程被谁阻塞,分析导致阻塞的源头
SELECT * FROM sys.sysprocesses WHERE spid =@spid --这是你要分析的进程ID
--查看此进程执行的SQL 语句
DBCC inputbuffer(@spid);
--如果想要结束当前进程,KILL 掉当前导致阻塞的SQL
KILL @spid
二、分析死锁还是阻塞
USE master;
GO
DECLARE @spid INT,@bl INT;
DECLARE s_cur CURSOR FOR
SELECT 0,blocked FROM sys.sysprocesses a
WHERE blocked > 0
AND NOT EXISTS( SELECT 1 FROM sys.sysprocesses b WHERE b.blocked > 0 AND a.blocked = b.spid)
UNION
SELECT spid,blocked FROM sys.sysprocesses WHERE blocked > 0;
OPEN s_cur;
FETCH NEXT FROM s_cur
INTO @spid,
@bl;
WHILE @@FETCH_STATUS = 0
BEGIN
IF @spid = 0
SELECT '进程号SPID:[' + CAST(@bl AS VARCHAR(10)) + ']引起死锁,其执行的SQL语法如下';
ELSE
SELECT '进程号SPID:[' + CAST(@spid AS VARCHAR(10)) + ']被' + ' 进程号SPID:[' + CAST(@bl AS VARCHAR(10)) + ']阻塞,其当前进程执行的SQL语法如下';
DBCC INPUTBUFFER(@bl);
FETCH NEXT FROM s_cur INTO @spid,@bl;
END;
CLOSE s_cur;
DEALLOCATE s_cur;