Wednesday, October 10, 2012

Kill All Connections to a Particular Database in SQL Server

Today I had to kill connections for a particular database which had atleast 20connections.

If It had just couple of connections it would be easy to kill them manually by using kill command.
Ex
Kill 56


But if you have more than 10connections for a database and want to kill all of them at one go then below is a script that would be helpful.

Execute below Script on Master Database which creates a StoreProcedure usp_killspids.

 ----------------------------------------------------------------------------------------------------------------------------------------------
USE [master]
GO
/****** Object:  StoredProcedure [dbo].[usp_killspids]    Script Date: 11/13/2010 08:28:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[usp_killspids]   
    @dbname varchar(100) 
as   
declare @spid int   
declare @variable varchar(200) 
declare @lastspid bigint
select top 1 @lastspid=spid from master..sysprocesses order by spid desc
select top 1 @spid=spid from  
master..sysdatabases sysd    
inner join   
master..sysprocesses sysp    
on   
sysd.dbid=sysp.dbid   
where    
sysd.name=@dbname and spid <> @@spid 
while @spid <= @lastspid  
begin   
    if @spid in (
    select spid from  
    master..sysdatabases sysd    
    inner join   
    master..sysprocesses sysp    
    on   
    sysd.dbid=sysp.dbid   
    where    
    sysd.name=@dbname   
    and   
    spid <> @@spid )
    begin

    set @variable='kill '+Convert(varchar(5),@spid) 
    exec (@variable) 
    end
set @spid=@spid+1
end

 ----------------------------------------------------------------------------------------------------------------------------------------------

Once the usp_killspids StoreProc is created you can use as below.

Ex.

Exec usp_killspids 'AdventureWorks2008'

1 comment:

  1. good work, thanks for share this script, i would like to recommend you add spid>50, for kill connections to the master database without errors in execution

    ReplyDelete