2

我正在尝试创建一个 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
4

2 回答 2

6

试试这个——

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
于 2013-07-03T06:54:20.330 回答
1

您缺少一种通过@spid_table. 你应该在你的while后面添加两行exec

DELETE FROM @spid_table WHERE spid = @count
SELECT @count = spid FROM @spid_table

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

于 2013-07-03T07:02:13.790 回答