Link to home
Start Free TrialLog in
Avatar of CFS_developer
CFS_developer

asked on

Dependable query to determine who is connected to a database

I want to programmatically restore a database from backup.  But in order to do so, one must first break all existing connections to that database.  The following queries list NEARLY all connections:

select spid, rtrim(loginame) from sys.sysprocesses where db_name(dbid)='MyDatabaseName'
sp_who
sp_who2

Unfortunately, those queries do not always list every last connection.  Once in a while, those queries miss a connection.  After running one of the above queries, it is easy enough to kill all reported user connections.  Unfortunately, this process does not always report and kill every connection.  I need a query to show every last connection to a database so that I can kill those connections and then restore that database from backup.

Oddly enough, the following commands do not assist whatsoever:
alter database MyDatabaseName set offline with rollback immediate
alter database MyDatabaseName set online
alter database MyDatabaseName set single_user with rollback immediate
ASKER CERTIFIED SOLUTION
Avatar of Scott Pletcher
Scott Pletcher
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of CFS_developer
CFS_developer

ASKER

Thanks for the suggestion.  Hopefully keeping the database offline will resolve the few restore failures I used to have.