Home > Functions and DMVs, SQL Queries, SQL Server, T-SQL > Script to drop all connections to a Database

Script to drop all connections to a Database

There are instances when we may have to drop all the connections to a database for example to rename a database. The script below can be used to drop all the connections to the database.

DECLARE @dbname nvarchar(128)
SET @dbname = 'DB name here' -- db to drop connections 
DECLARE @processid int 
SELECT @processid = min(spid) 
from master.dbo.sysprocesses 
where dbid = db_id(@dbname) 
WHILE @processid IS NOT NULL 
BEGIN 
EXEC ('KILL ' + @processid) 
SELECT @processid = min(spid) 
from master.dbo.sysprocesses 
where dbid = db_id(@dbname) 
END
About these ads
  1. December 1, 2010 at 4:45 am | #1

    Very cool. Exactly what I needed. Thanks man!!

  1. February 8, 2010 at 4:10 pm | #1
  2. December 3, 2010 at 7:04 pm | #2

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: