Thursday 11 March 2010

Kill all connections in a database

Every now and then I've come across situations where you need to drop all connections to a database, so I came up with a little proc to auto generate and execute KILL statements against all processes for a certain database.

My original code for this was titled sp_massmurder_db, and was as follows.

 CREATE PROC [dbo].[sp_MassMurder_DB] @DBName varchar(100)
 AS
 

 SET NOCOUNT ON
 

 DECLARE @Spid int, @SQL Varchar (1000)
 

 DECLARE DESTROY CURSOR FOR
 SELECT spid
 FROM master.dbo.sysprocesses (NOLOCK)
 WHERE dbid = DB_ID(@DBName)
 

 OPEN DESTROY
 FETCH NEXT FROM DESTROY INTO @spid
 WHILE @@FETCH_STATUS = 0
  BEGIN
 

   SET @SQL = 'KILL ' + CONVERT(Varchar, @SPID)
   EXEC (@SQL)
   FETCH NEXT FROM DESTROY INTO @spid
 

  END
 CLOSE DESTROY
 DEALLOCATE DESTROY

No comments:

Post a Comment