Welcome to Julian Kuiters Monday, May 21 2018 @ 07:47 AM AEST

Snippet: Drop all connections to a database

  • Contributed by:
SQL Server 2000

If you want to drop all the connections on you sql server that are accessing a particular database, here's some code:

USE master
go

DECLARE @dbname sysname

SET @dbname = 'name of database you want to drop connections from'

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

Another method you could use would be to take the database offline for a moment:

USE master
GO

ALTER DATABASE dbname
SET OFFLINE WITH ROLLBACK IMMEDIATE
ALTER DATABASE dbname
SET ONLINE