Wednesday, February 15, 2012

T-SQL for killing active connections to your database

Here is some handy t-sql for killing active connections to your database. Replace 'DB_NAME' with the name of your database.
USE master 
GO 
 
SET NOCOUNT ON 
DECLARE @DBName varchar(50) 
DECLARE @spidstr varchar(8000) 
DECLARE @ConnKilled smallint 
SET @ConnKilled=0 
SET @spidstr = '' 
 
Set @DBName = 'DB_NAME' 
IF db_id(@DBName) < 4 
BEGIN 
PRINT 'Connections to system databases cannot be killed' 
RETURN 
END 
SELECT @spidstr=coalesce(@spidstr,',' )+'kill '+convert(varchar, spid)+ '; ' 
FROM master..sysprocesses WHERE dbid=db_id(@DBName) 
 
IF LEN(@spidstr) > 0 
BEGIN 
EXEC(@spidstr) 
SELECT @ConnKilled = COUNT(1) 
FROM master..sysprocesses WHERE dbid=db_id(@DBName) 
END