Sql Server 死锁查询和解除示例

2022-11-12 09:56:13
内容摘要
这篇文章主要为大家详细介绍了Sql Server 死锁查询和解除示例,具有一定的参考价值,可以用来参考一下。 对此感兴趣的朋友,看看idc笔记做的技术笔记。SQL代码如下: /* exec ma
文章正文

这篇文章主要为大家详细介绍了Sql Server 死锁查询和解除示例,具有一定的参考价值,可以用来参考一下。

对此感兴趣的朋友,看看idc笔记做的技术笔记。SQL代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
<code class="sql">
/*
 
exec master.dbo.p_lockinfo 0,0  ---显示死锁的进程,不显示正常的进程
 
exec master.dbo.p_lockinfo 1,0  ---杀死死锁的进程,不显示正常的进程
 
*/
 
Create  proc p_lockinfo
 
@kill_lock_spid bit=1,  --是否杀掉死锁的进程,1 杀掉, 0 仅显示
 
@show_spid_if_nolock bit=1 --如果没有死锁的进程,是否显示正常进程信息,1 显示,0 不显示
 
as
 
declare @count int,@s nvarchar(1000),@i int
 
select id=identity(int,1,1),标志,
 
进程ID=spid,线程ID=kpid,块进程ID=blocked,数据库ID=dbid,
 
数据库名=db_name(dbid),用户ID=uid,用户名=loginame,累计CPU时间=cpu,
 
登陆时间=login_time,打开事务数=open_tran, 进程状态=status,
 
工作站名=hostname,应用程序名=program_name,工作站进程ID=hostprocess,
 
域名=nt_domain,网卡地址=net_address
 
into #t from(
 
select 标志='死锁的进程',
 
spid,kpid,a.blocked,dbid,uid,loginame,cpu,login_time,open_tran,
 
status,hostname,program_name,hostprocess,nt_domain,net_address,
 
s1=a.spid,s2=0
 
from master..sysprocesses a join (
 
select blocked from master..sysprocesses group by blocked
 
)b on a.spid=b.blocked where a.blocked=0
 
union all
 
select '|_牺牲品_>',
 
spid,kpid,blocked,dbid,uid,loginame,cpu,login_time,open_tran,
 
status,hostname,program_name,hostprocess,nt_domain,net_address,
 
s1=blocked,s2=1
 
from master..sysprocesses a where blocked<>0
 
)a order by s1,s2
 
select @count=@@rowcount,@i=1
 
if @count=0 and @show_spid_if_nolock=1
 
begin
 
insert #t
 
select 标志='正常的进程',
 
spid,kpid,blocked,dbid,db_name(dbid),uid,loginame,cpu,login_time,
 
open_tran,status,hostname,program_name,hostprocess,nt_domain,net_address
 
from master..sysprocesses
 
set @count=@@rowcount
 
end
 
if @count>0
 
begin
 
create table #t1(id int identity(1,1),a nvarchar(30),b Int,EventInfo nvarchar(255))
 
if @kill_lock_spid=1
 
begin
 
declare @spid varchar(10),@标志 varchar(10)
 
while @i<=@count
 
begin
 
select @spid=进程ID,@标志=标志 from #t where id=@i
 
insert #t1 exec('dbcc inputbuffer('+@spid+')')
 
if @标志='死锁的进程' exec('kill '+@spid)
 
set @i=@i+1
 
end
 
end
 
else
 
while @i<=@count
 
begin
 
select @s='dbcc inputbuffer('+cast(进程ID as varchar)+')' from #t where id=@i
 
insert #t1 exec(@s)
 
set @i=@i+1
 
end
 
select a.*,进程的SQL语句=b.EventInfo
 
from #t a join #t1 b on a.id=b.id
 
end
---- 来自www.512pic.com </code>

注:关于Sql Server 死锁查询和解除示例的内容就先介绍到这里,更多相关文章的可以留意

代码注释

作者:喵哥笔记

IDC笔记

学的不仅是技术,更是梦想!