How do you kick users out of a SQL Server 2008 database?
I always use the following:
USE master; -- get out of dbname myself
GO
-- kick all other users out:
ALTER DATABASE [dbname] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
-- prevent sessions from re-establishing connection:
ALTER DATABASE [dbname] SET OFFLINE;
Sometimes this may take a while, and sometimes it is blocked because you're the one running it, and you have an active connection to the database. Check for other query windows that might have the same database context - this can include open dialogs, Object Explorer, IntelliSense, long-running jobs, etc.
When I'm done making my changes to that database's config, I simply:
ALTER DATABASE [dbname] SET ONLINE;
ALTER DATABASE [dbname] SET MULTI_USER;
Though, sometimes, the thing I need to do to that database requires the database to be online, so sometimes I have to leave it in single-user mode and do this:
ALTER DATABASE [dbname] SET ONLINE;
GO
USE [dbname];
Now I can make my changes, and then when I'm ready for other users to connect, simply:
ALTER DATABASE [dbname] SET MULTI_USER;
There are two ways of doing it:
Right click on the database in Object Explorer go to Tasks > Detach. Select the Drop Connections checkbox.
Set the database to single-user mode as outlined here:
-- hit Ctrl+Shift+M in SSMS to fill in the template parameter USE master; GO ALTER DATABASE N'<Database Name, sysname,>' SET SINGLE_USER WITH ROLLBACK IMMEDIATE; GO ALTER DATABASE N'<Database Name, sysname,>' SET READ_ONLY; GO ALTER DATABASE N'<Database Name, sysname,>' SET MULTI_USER; GO
I normally set database in single_user and then waitfor delay and then set the database back in multiuser as below :
-- to kill all connections for particular db ... otherwise the restore will fail as exclusive lock cannot be obtained for the db being restored.
alter database db_name
set single_user with rollback immediate
waitfor delay '00:00:05' -- wait for 5 secs
alter database db_name
set multi_user
restore database db_name from disk = 'D:\restore\db_name.bak'
with replace, stats = 10, recovery -- if you want to recover your database online
-- optional if you dont have the same directory/file structure
move 'datafile logical name' to 'E:\data\physical_name.mdf',
move 'logfile logical name' to 'F:\log\physical_name_log.ldf'