HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMajor

How do you kick users out of a SQL Server 2008 database?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
2008yousqlusersdatabasehowserverkickout

Problem

We need to do a restore, and cannot because other users are connected.
We thought we had disconnected every process, but apparently not.

How can we, from Management Studio, kick off everyone else so we can do this backup?

Solution

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;

Code Snippets

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;
ALTER DATABASE [dbname] SET ONLINE;
ALTER DATABASE [dbname] SET MULTI_USER;
ALTER DATABASE [dbname] SET ONLINE;
GO
USE [dbname];
ALTER DATABASE [dbname] SET MULTI_USER;

Context

StackExchange Database Administrators Q#6031, answer score: 45

Revisions (0)

No revisions yet.