处理sql server的死锁 [kill spid]
其他
2018-08-15 05:19:31
阅读次数: 0
- 死锁会照成管理--活动监视器打不开
- select * from sysprocesses where blocked>0
- 可以查出来锁的线程,blocked那一列就是需要kill掉的。
- exec('kill blocked列')
-
- use master
- go
- 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 @@ERROR<>0 RETURN @@ERROR
-
- insert into #tmp_lock_who(spid,bl) select 0 ,blocked
- from (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>0
-
- IF @@ERROR<>0 RETURN @@ERROR
-
-
- select @intCountProperties = Count(*),@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
- if @spid =0
- select '引起数据库死锁的是: '+ CAST(@bl AS VARCHAR(10)) + '进程号,其执行的SQL语法如下'
- else
- 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
-
- use master
- go
-
- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[p_killspid]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
- drop procedure [dbo].[p_killspid]
- GO
-
- create proc p_killspid
- @dbname varchar(200)
- as
- declare @sql nvarchar(500)
- declare @spid nvarchar(20)
-
- declare #tb cursor for
- select spid=cast(spid as varchar(20)) from master..sysprocesses where dbid=db_id(@dbname)
- open #tb
- fetch next from #tb into @spid
- while @@fetch_status=0
- begin
- exec('kill '+@spid)
- fetch next from #tb into @spid
- end
- close #tb
- deallocate #tb
- go
- exec master..sp_who_lock
- exec master..sp_who_lock
-
- exec master..p_killspid 'dbname'
-
转载自blog.csdn.net/heizistudio/article/details/77638949