Kill active connections to the database

by Allan Svelmøe Hansen November 28, 2007 12:38

This script is able to kill the active connections to a database in case you need an exclusive lock for example.

As always, do remember to back up your database(s) before running strange new scripts. I've not had any illeffects from using it, as it simply only closes the connections, and modifies nothing else, but hey - "real men don't backup, they just cry alot". So backup is a good idea before doing anything new.

Anyways - the script.

USE master

SET NOCOUNT ON;

DECLARE @SPIDToKill INT
DECLARE 
@KillQuery VARCHAR(400)
DECLARE @DBName VARCHAR(200)
SET @DBName 'DATABASE NAME HERE'


--First check if it is needed to run.
IF EXISTS(
    
SELECT T1.SPID
    
FROM SYSPROCESSES T1
    
INNER JOIN SYSDATABASES T2 ON T1.DBID=T2.DBID
    
WHERE T2.NAME=@DBName
BEGIN
    PRINT
('Active Connections')
    
--Create table for the session id's
    
DECLARE @SPIDTable TABLE (SPID INT)
    
--insert into the table
    
INSERT INTO @SPIDTable
    
SELECT T1.SPID
    
FROM SYSPROCESSES T1
    
INNER JOIN SYSDATABASES T2 ON T1.DBID=T2.DBID
    
WHERE T2.NAME=@DBName

    
--Declare a cursor to run through the SPIDTable entities
    
DECLARE SPID_CURSOR CURSOR FOR
    SELECT 
FROM @SPIDTable

    
OPEN SPID_CURSOR
    
FETCH NEXT FROM SPID_CURSOR INTO @SPIDToKill
    
--while we can fetch IDs from SPIDTable
    
WHILE(@@FETCH_STATUS =0BEGIN
        PRINT
('Attempting to kill SPID: ' CONVERT(VARCHAR,@SPIDToKill))
        
--Build the kill query
        
SET @KillQuery 'KILL 'LTRIM(STR(@SPIDToKill))
        
--exec it.
        
EXEC (@KillQuery)
        
FETCH NEXT FROM SPID_CURSOR INTO @SPIDToKill
    
END
    
--clean up
    
CLOSE SPID_CURSOR
    
DEALLOCATE SPID_CURSOR
END ELSE BEGIN
    PRINT
('No active connections')
END 
 

Bookmark and Share DotnetKicks dotnetshoutout

Powered by BlogEngine.NET 1.6.1.0
Theme by Mads Kristensen | Modified by Mooglegiant

About:
Allan Svelmøe Hansen

My real name is Allan Svelmøe Hansen.
I live in Denmark, where I work as a developer for hedal:kruse:brohus using SQL Server and the .NET framework since 2004.
My primary fields of expertise is back-end data integration, database design and optimization.


       View Allan Svelmøe Hansen's profile on LinkedIn     

Disclaimer

The opinions expressed herein are my own personal opinions and thoughts and does not represent my employers view in any way, nor are my results guaranteed for all situations.
Content is presented "as is", with no warranty.