SQL脚本杀死所有被阻止的进程?

时间:2013-07-03 06:49:19

标签: sql sql-server kill kill-process

我正在尝试创建一个可以杀死所有被阻止进程的SQL脚本。

我错过了什么吗?

declare @max_count int, @count int, @sqlstring varchar(100)
declare @spid_table table (spid int NOT NULL)

INSERT @spid_table
select spid
from master.dbo.sysprocesses
where spid in (select blocked from master.dbo.sysprocesses where blocked > 0) 

select @max_count = MAX(spid) FROM @spid_table
select top 1 @count = spid from @spid_table

while @count <= @max_count
begin
select @sqlstring = 'kill ' + CONVERT(varchar(4), @count)
exec(@sqlstring)
end

2 个答案:

答案 0 :(得分:5)

试试这个 -

DECLARE @SQL NVARCHAR(MAX)

SELECT @SQL = STUFF((
    SELECT CHAR(13) + 'KILL ' + CAST(spid as VARCHAR(5))
    FROM master.dbo.sysprocesses
    WHERE blocked != 0
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')

PRINT @SQL

EXEC sys.sp_executesql @SQL

答案 1 :(得分:1)

您错过了通过@spid_table递增的方法。您应该在while

之后的exec内添加两行
DELETE FROM @spid_table WHERE spid = @count
SELECT @count = spid FROM @spid_table

或将IDENTITY列添加到@spid_table并将其用于循环。