Snippet: Drop all connections to a database (SQL 2005)
If you want to drop all the connections to a database immediately, you can use the following commands:
USE master
GO
ALTER DATABASE database name
SET OFFLINE WITH ROLLBACK IMMEDIATE
ALTER DATABASE database name
SET ONLINE
GO
ALTER DATABASE database name
SET OFFLINE WITH ROLLBACK IMMEDIATE
ALTER DATABASE database name
SET ONLINE
Alternatively you can kill all the processes using a database with this 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
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

1 comment:
Awesome script, it solved my problem. Worked for me like a charm. Thanks for sharing it.
Post a Comment