創建存儲過程sp_who_lock,查詢死鎖的進程

create procedure sp_who_lock WITH ENCRYPTION 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 @@ERROR <> 0 RETURN @@ERROR insert into #tmp_lock_who(spid,bl) select spid,blocked from sysprocesses where blocked <> 0 IF @@ERROR <> 0 RETURN @@ERROR -- 找到臨時表的記錄數 select @intCountProperties = Count(1),@intCounter = 1 from #tmp_lock_who IF @@ERROR <> 0 RETURN @@ERROR if @intCountProperties=0 select '現在沒有阻塞和死鎖信息' as 'message' -- 循環開始 while @intCounter = @intCountProperties begin -- 取第一條記錄 select @spid = spid,@bl = bl from #tmp_lock_who where Id = @intCounter begin select '進程號SPID:'+ CAST(@spid AS VARCHAR(10))+ '被' + '進程號SPID:'+ CAST(@bl AS VARCHAR(10)) +'阻塞,其當前進程執行的SQL語法如下' DBCC INPUTBUFFER (@bl ) end -- 循環指針下移 set @intCounter = @intCounter + 1 end drop table #tmp_lock_who return 0 end
下面我們自己構建一個死鎖進程:

BEGIN TRANSACTION--開始事務 update T_Users set UserName='00000' where UserId='123' WAITFOR DELAY '01:00'; --指定1點執行
執行查詢語句:
select * from T_Users where UserId='123'
這時會發現一直在執行查詢。得不到查詢結果,我們執行第一步創建的存儲過程sp_who_lock.得到結果如下:
此時我們只需執行
kill 53
然后再執行查詢語句就可以得到結果了。