Created
September 1, 2015 20:17
-
-
Save JosiahSiegel/deb7354f00cc4b8a38f9 to your computer and use it in GitHub Desktop.
#MSSQL Auto KILL SPIDs based upon job name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DECLARE @spid INT | |
DECLARE @kill_spid NVARCHAR(100) | |
DECLARE running_jobs CURSOR FOR | |
SELECT | |
req.session_id | |
FROM sys.dm_exec_requests req | |
LEFT JOIN sys.dm_exec_sessions ses ON ses.session_id = req.session_id | |
LEFT JOIN msdb.dbo.sysjobs jobs ON SUBSTRING(ISNULL(ses.[program_name],''),CHARINDEX('0x', ISNULL(ses.[program_name],'')) + 18, 16) = SUBSTRING(REPLACE(ISNULL(jobs.[job_id],''), '-',''),17,16) | |
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext | |
WHERE jobs.name = 'MyJob' | |
OPEN running_jobs | |
FETCH NEXT FROM running_jobs INTO @spid | |
WHILE @@FETCH_STATUS = 0 | |
BEGIN | |
SET @kill_spid = 'kill ' + CAST(@spid AS VARCHAR(50)) | |
PRINT @kill_spid | |
EXECUTE sp_executesql @kill_spid | |
FETCH NEXT FROM running_jobs INTO @spid | |
END | |
CLOSE running_jobs | |
DEALLOCATE running_jobs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment