How to disconnect all users in sql server except sa?
Asked Answered
T

1

8

I would like to disconnect all users from SQL Server except sa.

The need for this is:

I wrote a db maintenance utility for my ERP. Before running it I need to ask all users to logoff. So somehow I would like to give them a message (through ERP) "disconnecting in 5 minutes, please save your work and logoff or you'll be kicked out" and then after 5 minutes run the command on the server that disconnects all people. I want "sa" or anyway "1 specific user" not to be disconnected, since the db maintenance utilty will use that user for db connection.

I found this:

use master
alter database MyDatabase set offline with rollback immediate

but how to say "one specific user is an exception"?

Thermoelectricity answered 25/10, 2012 at 7:44 Comment(0)
I
10

Use single_user instead of offline:

alter database [DatabaseName] set single_user with rollback immediate

The initial "single user" will be the one issuing the alter database command. You could then proceed to only allow specific users to log on:

alter login [LoginName] disable
Incautious answered 25/10, 2012 at 7:52 Comment(3)
Perfect! single_user is what I was looking for.Thermoelectricity
How do I identify the single user?Macneil
@Macneil You can use exec sp_whoIncautious

© 2022 - 2024 — McMap. All rights reserved.