Login or Sign Up to become a member!
LessThanDot Site Logo

LessThanDot

Community Wiki

Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot facebook Lessthandot rss

Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.

Navigation

Google Ads

Kill All Active Connections To A Database

From Wiki

Jump to: navigation, search

To kill all the connections to your database you can use the ALTER DATABASE command. Sometimes you want to restore the database from a backup but can't because people are connected. Here is one way which will kick off all the users immediately


  1. ALTER DATABASE YourDatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE
  2.  
  3. --do you stuff here
  4.  
  5. ALTER DATABASE YourDatabase SET MULTI_USER


The code below will wait 60 seconds

  1. ALTER DATABASE YourDatabase SET SINGLE_USER WITH ROLLBACK AFTER 60 SECONDS
  2.  
  3. --do you stuff here
  4.  
  5. ALTER DATABASE YourDatabase SET MULTI_USER

The reason this is better than looping over sysprocesses or sys.dm_exec_sessions is that nobody will connect while that looping piece of code runs


Contributed by: --SQLDenis 16:30, 4 June 2008 (GMT)

Part of SQL Server Admin Hacks

333 Rating: 3.9/5 (72 votes cast)