在某些报告生成中,我们在SQL Server中遇到死锁问题,所以我能做的就是
select *
from sys.sysprocesses
where dbid = db_id()
and spid <> @@SPID
and blocked <> 0
and lastwaittype LIKE 'LCK%'
dbcc inputbuffer (SPID from above query result)
dbcc inputbuffer (blocked from above query result)
如果EventInfo
列包含'mytext',我想通过
Kill 53
53
不是SPID或阻止我看到我要杀死其连接的特定文本
我希望每当死锁创建并找到特定单词时就会自动执行此过程。没有用户间隔或行动。
答案 0 :(得分:1)
从上面的ans,我按照我的要求改变。
/*drop table #inputbuffer
--First Time create Table
create table #inputbuffer
(eventType varchar(255) ,
parameters int ,
procedureText varchar(255),
spid varchar(6))
*/
declare @spid varchar(6)
declare @sql varchar(50)
declare sprocket cursor fast_forward for
select spid from SYS.sysprocesses
where dbid =db_id() and spid <> @@SPID and blocked <>0 and lastwaittype LIKE 'LCK%'
union all
select blocked from SYS.sysprocesses
where dbid =db_id() and spid <> @@SPID and blocked <>0 and lastwaittype LIKE 'LCK%'
open sprocket
fetch next from sprocket into
@spid
while @@fetch_status = 0
begin
set @sql = 'dbcc inputbuffer(' + @spid + ')'
insert into #inputbuffer(eventType, parameters, procedureText)
exec (@sql)
update #inputbuffer
set spid = @spid
where spid is null
fetch next from sprocket into
@spid
end
close sprocket
deallocate sprocket
if @@cursor_rows <> 0
begin
close sprocket
deallocate sprocket
end
DELETE from #inputbuffer where procedureText NOT like '%SUBLED%'
select spid, eventType, parameters, procedureText from #inputbuffer
DECLARE @n int,
@i int= 0,
@s int,
@kill nvarchar(20)= 'kill ',
@sqln nvarchar (255)
SELECT @n = COUNT(*) FROM #inputbuffer
WHILE @i < @n
BEGIN
SELECT TOP 1 @s = spid from #inputbuffer
SET @sqln = @kill + cast(@s as nvarchar(10))
select @sqln
EXECUTE sp_executesql @sqln
delete from #inputbuffer where spid = @s
SET @i = @i + 1
END
答案 1 :(得分:0)
有时我会使用这个旧查询来删除具有特定描述的会话:
declare @t table (sesid int)
--Here we put all sessionid's with specific description into temp table
insert into @t
select spid
from sys.sysprocesses
where dbid = db_id()
and spid <> @@SPID
and blocked <> 0
and lastwaittype LIKE 'LCK%'
DECLARE @n int,
@i int= 0,
@s int,
@kill nvarchar(20)= 'kill ',
@sql nvarchar (255)
SELECT @n = COUNT(*) FROM @t
--Here we execute `kill` for every sessionid from @t in while loop
WHILE @i < @n
BEGIN
SELECT TOP 1 @s = sesid from @t
SET @sql = @kill + cast(@s as nvarchar(10))
--select @sql
EXECUTE sp_executesql @sql
delete from @t where sesid = @s
SET @i = @i + 1
END
答案 2 :(得分:0)
这是更简洁的查询,可以杀死运行特定sql的所有会话。
DECLARE @kill varchar(8000); SET @kill = '';
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), session_id) + ';'
FROM sys.dm_exec_requests CROSS APPLY sys.dm_exec_sql_text(sql_handle)
WHERE database_id = db_id('dldb') and session_id <> @@SPID
and text like '%FROM dl2ResultsHeaderItemSubTree%'
EXEC(@kill);
从SQL Server 2005开始有效。
从List the queries running on SQL Server和Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK)合并。