tags:

views:

391

answers:

2

I'm doing active development on my schema in SQL Server 2008 and frequently want to rerun my drop/create database script. When I run

USE [master]
GO

IF  EXISTS (SELECT name FROM sys.databases WHERE name = N'MyDatabase')
DROP DATABASE [MyDatabase]
GO

I often get this error

Msg 3702, Level 16, State 4, Line 3
Cannot drop database "MyDatabase" because it is currently in use.

If you right click on the database in the object explorer pane and select the Delete task from the context menu, there is a checkbox which to "close existing connections"

Is there a way to specify this option in my script?

+7  A: 

You can disconnect everyone and roll back their transactions with:

alter database [MyDatbase] set single_user with rollback immediate

After that, you can safely drop the database :)

Andomar
I've used this but often wondered if there was a window of opportunity for another user to get in as the "single user" - is that possible? Possible alternative is ALTER DATABASE [MyDatabaseName] SET OFFLINE WITH ROLLBACK IMMEDIATE
Kristen
The user in single_user is you; unless you disconnect after setting single user mode. Then one (1) other user can log on.
Andomar
Thanks; makes sense.
Kristen
Once you've dropped the database, if you create a new one with the same name I presume it will be in multi_user mode? So you don't have to run: alter database [MyDatbase] set multi_user
AndyM
@AndyM: Yeah, multi_user is probably the default
Andomar
+1  A: 

Go to management studio and do everything you describe, only instead of clicking OK, click on Script. It will show the code it will run which you can then incorporate in your scripts.

In this case, you want:

ALTER DATABASE [MyDatabase] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
hgimenez
I was going to try to answer this question by doing exactly what you describe (scripting the "delete database" dialog) but it **doesn't** add the ALTER DATABASE line to the script if you check the "close existing connections" checkbox.
Matt Hamilton
The script generating from the wizard included the 'alter database' line for me.
nick
Weird. Which Management Studio version? I'm on 2008 x64.
Matt Hamilton
Me too:Microsoft SQL Server Management Studio 10.0.1600.22 Operating System 6.0.6001
nick