Locked Databases
Every so often, I’ll run into a database that’s locked and I want to be able to change something about it and cannot. One way to see what is using the database in question is to run the activity monitor in SQL SMS. From the activity monitor, you can kill a process from this screen by right-clicking the process and selecting the “Kill Process” option. Unfortunately, I’ve had a few cases where the connections are on timers, so the connections come right back and lock the database again and I get the locked message again.
However, there is a way around this. By setting the database as a single user database and rolling back all opened transactions, you can allow yourself the time to make the changes needed.
alter database <Database Name> set single_user with rollback immediate
After running the command above, you should see the following result:
“Nonqualified transactions are being rolled back. Estimated rollback completion: 100%.”
After this is ran, only 1 user can now be connected to your database. Just remember, the single user that is connected at that time is the window (or ADO connection) that you run this statement from. If you close your connection, the single connection could be taken by another process. So it’s probably best to have your changes ready in T-SQL to run after you run the statement to alter database to single user. If you are just running this to close all open connections (and there isn’t some process that auto-reconnects), then you can just run the statement below to alter the database back. All open connections (except the current window/connection you are in) were closed by the first statement.
Running this next alter statement sets the database to allow multiple users again. Any connection that was closed by the first statement will remain closed.
alter database <Database Name> set multi_user with rollback immediate
After the command runs successfully, you will see the following result:
“Command(s) completed successfully.”
So if you ever run into an issue where a connection is keeping you from processing changes that need to be made, first try the activity monitor. If the connection(s) still persists, setting the database to single_user is good way to lock out other connections as long as it is handled correctly.