Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop DB using MSBuild even if in use

I am using the following command in my MSBuild file to drop a database

sqlcmd -E -S <ServerName> -Q "DROP DATABASE <DBName>"

But sometimes I get the error

Cannot drop database because it is currently in use.

What command should I use so that the DB is dropped even if it is in use?

like image 610
Achinth Gurkhi Avatar asked Jan 27 '12 16:01

Achinth Gurkhi


2 Answers

You can set your database to SINGLE_USER to drop all existing connections.

sqlcmd -E -S <ServerName> -Q "ALTER DATABASE <DBName> SET SINGLE_USER WITH ROLLBACK IMMEDIATE"
sqlcmd -E -S <ServerName> -Q "DROP DATABASE <DBName>"

This is preferred to looping over each of the connections and dropping them one by one, because some applications will immediately reconnect.

like image 185
Michael Fredrickson Avatar answered Oct 26 '22 11:10

Michael Fredrickson


To kill all connections to your database. See Kill All Active Connections To A Database

Now issue your DROP DATABASE command after the above procedure.

like image 34
Shankar Narayana Damodaran Avatar answered Oct 26 '22 11:10

Shankar Narayana Damodaran