Bookmark and Share

Wednesday, December 03, 2008

Sql server kill active connections

Here is a good TSQL query that eliminates all the active connections.

It's usefull when your code forgets to close the connection object.


SET NOCOUNT ON
DECLARE @spid INT,
@cnt INT,
@sql VARCHAR(255) ,
@dbname varchar(50)

set @dbname = 'mydbname'

SELECT @spid = MIN(spid), @cnt = COUNT(*)
FROM master..sysprocesses
WHERE dbid = DB_ID(@dbname)
AND spid != @@SPID

PRINT 'Starting to KILL '+RTRIM(@cnt)+' processes.'

WHILE @spid IS NOT NULL
BEGIN
PRINT 'About to KILL '+RTRIM(@spid)
SET @sql = 'KILL '+RTRIM(@spid)
EXEC(@sql)
SELECT @spid = MIN(spid), @cnt = COUNT(*)
FROM master..sysprocesses
WHERE dbid = DB_ID(@dbname)
AND spid != @@SPID
PRINT RTRIM(@cnt)+' processes remain.'
END



Found at: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=890339&SiteID=1

No comments:

Post a Comment