MS SQL - Kill connections to a database

2. February 2011 19:33

There can be times that you need to kill all connections to a data so that you can perform emergency maintenance. Or for some suitable reason either way you want to disappear the current people who are logged in.

So here is a little stored procedure that will do just that.

CREATE PROCEDURE [dbo].[KillConnectionsdb] @dbname varchar(MAX)
AS
	DECLARE @spid int
	DECLARE @sql varchar(MAX)

	DECLARE cur CURSOR FOR
		SELECT spid FROM sys.sysprocesses P
			JOIN sys.sysdatabases D ON (D.dbid = P.dbid)
			WHERE LTRIM(RTRIM(D.Name)) = @dbname
			AND P.spid != @@SPID

	OPEN cur

	FETCH NEXT FROM cur
		INTO @spid
		
	WHILE @@FETCH_STATUS = 0
	BEGIN
		PRINT CONVERT(varchar, @spid)

		SET @sql = 'KILL ' + RTRIM(@spid)
		PRINT @sql
		EXEC(@sql)

		FETCH NEXT FROM cur
			INTO @spid
	END

	CLOSE cur
	DEALLOCATE cur

GO

It is really simply to use.

Just call the stored procedure with in the following way where 'Testing' happens to be the name of the database you want to kill off all the connections.

EXEC KillConnectionsdb @dbname = 'Testing'

Note: the stored procedure will avoid attempting to kill its own connection in the process.

E-mail Kick it! DZone it! del.icio.us Permalink


Comments (1) -

2/8/2013 10:41:55 AM #

go

DECLARE @dbname sysname
SET @dbname = 'DATABASENAME'

DECLARE @spid int
SELECT @spid = min(spid) from master.dbo.sysprocesses where dbid = db_id(@dbname)
WHILE @spid IS NOT NULL
BEGIN
EXECUTE ('KILL ' + @spid)
SELECT @spid = min(spid) from master.dbo.sysprocesses where dbid = db_id(@dbname) AND spid > @spid
END

Katrina Keisy Republic of the Philippines | Reply

Pingbacks and trackbacks (1)+

Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading