<

Quickly Disconnect Users From a Database

Published on
9,542 Points
3,542 Views
Last Modified:
Approved
Disconnect All Users of a Database

There comes a time in every DBA’s life when he or she has many users connected to a database that needs to be detached, placed in single user mode, or simply refreshed.  The problem is they keep reconnecting more quickly than you can KILL them off.  This is especially true when you are working in an environment where the lines between testing and production are blurred.

Hopefully you know about the KILL command, and aren’t thinking I’m advocating becoming a serial killer.  Though a hatchet properly placed can cure a lot of problems, especially when you can get to the network cable!

To disconnect a user you can use sp_who2 and look at the users currently connected to the database in question.  Once you have the spid for the connection, you can issue the command:

KILL spid

The problem will be, you have to look at all the connections that are currently open, KILL those connections, then check sp_who2 again to see if any new connections were opened.  Then lather, rinse, repeat.  This process is tedious at best.

There is a better way.
The Solution

CREATE PROCEDURE kill_database_users @dbname sysname with recompile

AS

declare @spid smallint

declare @msg    varchar(255)

declare @dbid int

select

        @dbid = sdb.dbid

from    master..sysdatabases sdb

where   sdb.name = @dbname

declare db_users insensitive cursor for

select

        sp.spid

from    master..sysprocesses sp

where   sp.dbid = @dbid

open db_users

fetch next from db_users into @spid

while @@fetch_status = 0

        begin

        select @msg = 'kill '+convert(char(5),@spid)

        print @msg

        execute (@msg)

        fetch next from db_users into @spid

        end

close db_users

deallocate db_users

GO

This Should close out any connections to the @dbname in question.  Once it’s complete, you can then switch to single-user mode, or detach the database, or whatever else you may need to do.  Normally, I'd avoid a cursor, but this is one of those special cases where you want to sequentially work through a list, and perform a function.  That's strictly the domain of a cursor!

Enjoy!
0
Comment
0 Comments

Featured Post

Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

Join & Write a Comment

Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month