8

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?

Yuck
  • 49,664
  • 13
  • 105
  • 135
Achinth Gurkhi
  • 2,136
  • 4
  • 24
  • 45

6 Answers6

19

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.

Michael Fredrickson
  • 36,839
  • 5
  • 92
  • 109
3

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.

NoNaMe
  • 6,020
  • 30
  • 82
  • 110
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
0

Please use something like this:

sqlcmd -S servername\instance -Q"use master;DROP DATABASE yourdatabase"
François Févotte
  • 19,520
  • 4
  • 51
  • 74
Paul Voicu
  • 53
  • 1
  • 3
0

Try this:

sqlcmd -S .\MAPS -Q "RESTORE DATABASE Awards FROM DISK = 'C:\Awards_Project
\Awards_FULL.bak' WITH REPLACE, MOVE 'Awards' to 'C:\Awards_Project\Awards.mdf',
MOVE 'Awards_log' to 'C:\Awards_Project\Awards.ldf'" 
cheesemacfly
  • 11,622
  • 11
  • 53
  • 72
0

You could alternatively restart the sql service and then perform the drop e.g. in a myfile.bat

@echo off
REM Requires administrative rights to restart service
REM open powershell and execute command in administrative mode
powershell -Command "Start-Process 'cmd' -Verb RunAs -ArgumentList '/c net stop MSSQLSERVER && net start MSSQLSERVER && exit'"      
echo Please wait ~10 seconds for sql service to restart. 
Timeout /t 10 /nobreak
echo Dropping database. 
sqlcmd -S localhost -Q "drop database [database Name]"
benscabbia
  • 17,592
  • 13
  • 51
  • 62
-1

You cannot drop a database that is in use. Check link for ref

NoNaMe
  • 6,020
  • 30
  • 82
  • 110
Arran
  • 24,648
  • 6
  • 68
  • 78