Kill Active Processes for a particular SQL Database

Below is a SQL script that I use all the time when it comes down to hung procedures and any unwanted processes that are left open. This below T-SQL could also be turned into a procedure quite easily and used as a cleanup job before running any backups.



DECLARE @p_SPID int, 
@p_SQL nvarchar(2000),
@dbName nvarchar(100)

-- Change the 'Database Name' to the database that you intend to kill the processes for
SET @dbName = 'Database Name'

DECLARE #cur_Processes CURSOR FOR 
SELECT p.SPID FROM master.dbo.sysprocesses AS p JOIN master.dbo.sysdatabases AS d ON( d.dbid = p.dbid ) 
WHERE d.Name = @dbName AND p.SPID > 50 
-- AND spid >= 51 (because spids of 50 or less are reserved for internal use.) 

OPEN #cur_Processes 

FETCH NEXT 
FROM #cur_Processes INTO @p_SPID 

WHILE @@FETCH_STATUS = 0 

BEGIN SET @p_SQL = 'KILL ' + CONVERT( nvarchar(30), @p_SPID ) 

PRINT @p_SQL EXECUTE( @p_SQL ) 

FETCH NEXT FROM #cur_Processes INTO @p_SPID END 

CLOSE #cur_Processes 
DEALLOCATE #cur_Processes 


This entry was posted in Procedures, SQL. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>