Until now the only way to kill wayward commands or queries in SQL Server was to run sp_who or sp_who2, look for the record with abnormal CpuTime or DiskIO readings (or look for the login of the guy who never knows what he’s doing), and take note of the corresponding Spid number by running your finger along the screen tracing it back to the ID so you don’t get confused and end up killing the wrong Spid from another record by mistake.
But now there’s a better way if you know the the likely culprit you want to kill in advance. The script below will allow you to filter the results of sp_who2 based on any of the returned columns. You’ll now be able to specify the database name or login name etc. and the query will return only the rows that match your constraints. Narrow the results down enough and you’ll be left with one record to kill. Then copy the results of the KillSpid column and paste to a new SSMS window. Now you should be left with one Kill command to run with no possibility of killing the wrong Spid.
IF OBJECT_ID('tempdb..#sp_who2') IS NOT NULL DROP TABLE #sp_who2 GO CREATE TABLE #sp_who2 ( Spid INT ,Status VARCHAR(255) ,LoginName VARCHAR(255) ,HostName VARCHAR(255) ,BlkBy VARCHAR(255) ,DbName VARCHAR(255) ,Command VARCHAR(255) ,CpuTime INT ,DiskIO INT ,LastBatch VARCHAR(255) ,ProgramName VARCHAR(255) ,Spid2 INT ,RequestId INT ) INSERT INTO #sp_who2 EXEC sp_who2 SELECT 'Kill ' + CONVERT(VARCHAR(MAX), SPID) AS KillSpid ,Spid ,Status ,LoginName ,HostName ,BlkBy ,DbName ,Command ,CpuTime ,DiskIO ,LastBatch ,ProgramName ,Spid2 ,RequestId FROM #sp_who2 -- Add any filtering of the results here : WHERE DBName NOT IN ('master') -- Add any sorting of the results here : -- AND ProgramName = '' -- AND DbName = '' -- AND LoginName = '' -- AND HostName = '' -- AND Status = '' ORDER BY Spid ASC ,DBName ASC; DROP TABLE #sp_who2
1 thought on “How to filter sp_who2 to create KILL statements”