156

I want to drop a database. I have used the following code, but to no avail.

public void DropDataBase(string DBName,SqlConnection scon)
{
    try
    {
        SqlConnection.ClearAllPools();
        SqlCommand cmd = new SqlCommand("ALTER DATABASE " + DBName + "     SET SINGLE_USER     WITH ROLLBACK IMMEDIATE", scon);
        cmd.CommandType = CommandType.Text;
        scon.Open();
        cmd.ExecuteNonQuery();
        scon.Close();

        SqlCommand cmddrpdb = new SqlCommand("drop database " + DBName + "", scon);
        cmddrpdb.CommandType = CommandType.Text;
        scon.Open();
        cmddrpdb.ExecuteNonQuery();
        scon.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show("DropDataBase : " +ex.Message);
    }
}

I am getting Error as cannot drop database because it is currently in use. Please help me out in the above mentioned issue.

Alex Weitz
  • 3,199
  • 4
  • 34
  • 57
sachin kulkarni
  • 2,618
  • 7
  • 28
  • 33

21 Answers21

162

Before dropping a database, you will need to drop all the connections to the target database first.

I have found a solution at http://www.kodyaz.com/articles/kill-all-processes-of-a-database.aspx

DECLARE @DatabaseName nvarchar(50)
SET @DatabaseName = N'YOUR_DABASE_NAME'

DECLARE @SQL varchar(max)

SELECT @SQL = COALESCE(@SQL,'') + 'Kill ' + Convert(varchar, SPId) + ';'
FROM MASTER..SysProcesses
WHERE DBId = DB_ID(@DatabaseName) AND SPId <> @@SPId

--SELECT @SQL 
EXEC(@SQL)
unruledboy
  • 2,455
  • 2
  • 23
  • 30
139

It's too late, but it may be useful for future users.

You can use the below query before dropping the database query:

 use master go
 alter database [MyDatbase] set single_user with rollback immediate

 drop database [MyDatabase]

It will work. You can also refer to

How do I specify "close existing connections" in sql script

I hope it will help you :)

Hitesh
  • 3,508
  • 1
  • 18
  • 24
83

Someone connected to the database. Try to switch to another database and then, to drop it:

Try

SP_WHO to see who connected

and KILL if needed

Brian J
  • 694
  • 1
  • 21
  • 34
Gregory Nozik
  • 3,296
  • 3
  • 32
  • 47
  • 27
    For SQL server mgmt. studio: Right click database: Properties -> Options -> Restrict Access : Set to "Single User" and perform the drop afterwards. – AceAlfred Sep 27 '13 at 11:02
  • invoke-sqlcmd -ServerInstance localhost 'exec sp_who' | where-object {$_.dbname -eq 'myDbName'} returns nothing. Yet it till complains. This doesn't seem to actually work. – Pxtl Mar 12 '20 at 21:56
  • 1
    @AceAlfred Yours is the easiest one among all. Should have been one of the answers. Thanks. – Amit Ray Nov 27 '20 at 06:08
58

For SQL server mgmt. studio:

Right click database: Properties -> Options -> Restrict Access : Set to "Single User" and perform the drop afterwards

AceAlfred
  • 1,111
  • 3
  • 21
  • 35
  • 1
    If you want to delete a database right from the Management Studio, this is the most intuitive solution. Thank you. – Andre Pena Jan 14 '16 at 18:05
  • 2
    I did it, and then used `drop database myDatabase`. It didn't solve the problem. the same error (`... it is currently is use`) happned. – Shahryar Saljoughi Sep 08 '20 at 13:11
  • @ShahryarSaljoughi I just followed acealfred 's instructions. Perhaps the menu approach executes some other commands beyond a simple drop. – Michael May 24 '21 at 22:28
47

In SQL Server Management Studio 2016, perform the following:

  • Right click on database

  • Click delete

  • Check close existing connections

  • Perform delete operation

DForck42
  • 19,789
  • 13
  • 59
  • 84
Shashi Dhar
  • 603
  • 6
  • 7
35
select * from sys.sysprocesses where dbid = DB_ID('Test')

(Replace 'Test' with the name of the database you are trying to drop) This will tell you which processes are using it.

If you still want to force drop then, the ultimate approach is:

USE master;
GO
ALTER DATABASE Test 
SET SINGLE_USER 
WITH ROLLBACK IMMEDIATE;
GO
DROP DATABASE Test;

Hope this helps !

Raza
  • 807
  • 1
  • 9
  • 16
9

First make your data base offline after that detach it e.g.

Use Master
GO
ALTER DATABASE dbname SET OFFLINE
GO
EXEC sp_detach_db 'dbname', 'true'
8

If your dropping the database in SQL Management Studio and you get the message, don't forget that you use Master as selected database otherwise your query is also an connection to the database.

USE Master;
GO
DROP DATABASE AdventureWorks;
GO
LockTar
  • 5,364
  • 3
  • 46
  • 72
8

First check the connected databases

SP_WHO

Second Disconnect your database

DECLARE @DatabaseName nvarchar(50)
SET @DatabaseName = N'your_database_name'

DECLARE @SQL varchar(max)

SELECT @SQL = COALESCE(@SQL,'') + 'Kill ' + Convert(varchar, SPId) + ';'
FROM MASTER..SysProcesses
WHERE DBId = DB_ID(@DatabaseName) AND SPId <> @@SPId

--SELECT @SQL 
EXEC(@SQL)

FINALLY DROP IT

drop database your_database
Sajid khan
  • 595
  • 5
  • 12
3

A brute force workaround could be:

  1. Stop the SQL Server Service.

  2. Delete the corresponding .mdf and .ldf files.

  3. Start the SQL Server Service.

  4. Connect with SSMS and delete the database.

HerbalMart
  • 1,669
  • 3
  • 27
  • 50
  • It works for me. Thanks. I think the problem is an external hard drive. I switched the file to a local disk. Thanks for your solution. – InfZero Nov 02 '14 at 21:16
3

To delete a database even if it's running, you can use this batch file

@echo off

set /p dbName= "Enter your database name to drop: " 

echo Setting to single-user mode
sqlcmd -Q "ALTER DATABASE [%dbName%] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE"

echo Dropping...
sqlcmd -Q "drop database %dbName%"

echo Completed.

pause

Screen

Alper Ebicoglu
  • 8,884
  • 1
  • 49
  • 55
2

I wanted to call out that I used a script that is derived from two of the answers below.

Props to @Hitesh Mistry and @unruledboy

DECLARE @DatabaseName nvarchar(50)
SET @DatabaseName = N'[[[DatabaseName]]]'

DECLARE @SQL varchar(max)

SELECT @SQL = COALESCE(@SQL,'') + 'Kill ' + Convert(varchar, SPId) + ';'
FROM MASTER..SysProcesses
WHERE DBId = DB_ID(@DatabaseName) AND SPId <> @@SPId

EXEC(@SQL)

alter database [[[DatabaseName]]] set single_user with rollback immediate

DROP DATABASE [[[DatabaseName]]]
Don Rolling
  • 2,301
  • 4
  • 30
  • 27
1

Using MS SQL Server 2008, in DELETE dialog with Close connection options, this is the generated script, I guess it is the best:

EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = N'YOUR_DATABASE_NAME'
GO
USE [master]
GO
ALTER DATABASE [YOUR_DATABASE_NAME] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
USE [master]
GO
/****** Object:  Database [YOUR_DATABASE_NAME]    Script Date: 01/08/2014 21:36:29 ******/
DROP DATABASE [YOUR_DATABASE_NAME]
GO
Luke Vo
  • 17,859
  • 21
  • 105
  • 181
  • This is what SQL Server Management Studio scripts out and what happens to work for me. The only thing I did differently was wrap all of that inside of a `USE [master] IF EXISTS(SELECT * FROM sys.databases WHERE name = 'Database_Name') BEGIN -- your script here END` – Smitty-Werben-Jager-Manjenson Aug 19 '20 at 23:19
1

Just wanted to give a vb.net (as with c language if want to convert..) I was having similar problem for uninstal of one of my programs, dropping the DB was bit tricky, yes could get users to go into server drop it using Express, but thats not clean, after few looks around got a perfect little bit of code together...

    Sub DropMyDatabase()
    Dim Your_DB_To_Drop_Name As String = "YourDB"
    Dim Your_Connection_String_Here As String = "SERVER=MyServer;Integrated Security=True"
    Dim Conn As SqlConnection = New SqlConnection(Your_Connection_String_Here)

    Dim AlterStr As String = "ALTER DATABASE " & Your_DB_To_Drop_Name & " SET OFFLINE WITH ROLLBACK IMMEDIATE"
    Dim AlterCmd = New SqlCommand(AlterStr, Conn)

    Dim DropStr As String = "DROP DATABASE " & Your_DB_To_Drop_Name
    Dim DropCmd = New SqlCommand(DropStr, Conn)

    Try
        Conn.Open()
        AlterCmd.ExecuteNonQuery()
        DropCmd.ExecuteNonQuery()
        Conn.Close()

    Catch ex As Exception
        If (Conn.State = ConnectionState.Open) Then
            Conn.Close()
        End If
        MsgBox("Failed... Sorry!" & vbCrLf & vbCrLf & ex.Message)
    End Try
End Sub

Hope this helps anyone looking xChickenx

UPDATE Using this converter here is the C# version :

public void DropMyDatabase()
    {
        var Your_DB_To_Drop_Name = "YourDB";
        var Your_Connection_String_Here = "SERVER=MyServer;Integrated Security=True";
        var Conn = new SqlConnection(Your_Connection_String_Here);

        var AlterStr = "ALTER DATABASE " + Your_DB_To_Drop_Name + " SET OFFLINE WITH ROLLBACK IMMEDIATE";
        var AlterCmd = new SqlCommand(AlterStr, Conn);

        var DropStr = "DROP DATABASE " + Your_DB_To_Drop_Name;
        var DropCmd = new SqlCommand(DropStr, Conn);

        try
        {
            Conn.Open();
            AlterCmd.ExecuteNonQuery();
            DropCmd.ExecuteNonQuery();
            Conn.Close();

        }
        catch(Exception ex)
        {
            if((Conn.State == ConnectionState.Open))
            {
                Conn.Close();
            }
            Trace.WriteLine("Failed... Sorry!" + Environment.NewLine + ex.Message);
        }
    }
Ognyan Dimitrov
  • 6,026
  • 1
  • 48
  • 70
Chicken
  • 428
  • 3
  • 11
  • 1
    The question needs a C# response, as it is tagged that way. – Mathias Lykkegaard Lorenzen Mar 25 '14 at 20:30
  • @MathiasLykkegaardLorenzen there are several freeware apps that can translate .NET code across all languages. There even online apps. – Ognyan Dimitrov Aug 25 '15 at 13:45
  • 1
    Point taken. I would have changed my vote, but I can't, as it is locked. – Mathias Lykkegaard Lorenzen Aug 25 '15 at 17:07
  • **BAD IDEA!** Dropping an database when it is offine will not remove the database files! Even if this might be handy in some special case, it's not a pattern you should blindly follow. Problems: a) your disk gets filled and b) you might run into issues when trying to recreate the database using the same physical files. – Stefan Steinegger Feb 21 '17 at 08:40
  • @OgnyanDimitrov One more reason to provide a C# answer. Otherwise why not post a python, powershell, c++, assembly ways of doing it? Or post it as base64 text for those who would want an answer written in base64? I am not downvoting or anything, but MathiasLykkegaardLorenzen point is valid. – P-L Aug 28 '23 at 13:53
1

All I did was switched the database from the top in SSMS to Master and then wrote drop database with the name of my DB and it worked perfectly. The issue was that I had the DB set to the same name as the DB I wanted to drop, thats why it was currently in use!

jon Thomas
  • 11
  • 1
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/34178442) – Standin.Wolf Apr 10 '23 at 20:49
1
  1. First you should Change Data Base State To Single User
  2. Then go to master Data Base
  3. And Finally Drop Data Base

For Example

My Data Base Name Is Test1

ALTER DATABASE Test1 SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO

USE master
GO
DROP DATABASE Test1
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
امید
  • 11
  • 2
0

just renaming the DB (to be delete) did the trick for me. it got off the hold of whatever process was accessing the database, and so I was able to drop the database.

AceMark
  • 701
  • 1
  • 11
  • 21
0

Go to available databases section and select master. Then Try DROP DATABASE the_DB_name.

0

Use this:

/* Delete Database Backup and Restore History from MSDB System Database */
EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = N'[dba]'
GO

/* Query to Get Exclusive Access of SQL Server Database before Dropping the Database  */
USE [master]
GO

ALTER DATABASE [dba]

SET SINGLE_USER
WITH

ROLLBACK IMMEDIATE
GO

/* Query to Drop Database in SQL Server  */
DROP DATABASE [dba]
GO
Francesco Mantovani
  • 10,216
  • 13
  • 73
  • 113
0

You cannot drop a database currently being used however you can use sp_detach_db stored procedure if you want to remove a database from the server without deleting the database files.

KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
0

When you drop the DB from the SSMS UI, it also kills all connections to this DB. enter image description here

FFFffff
  • 776
  • 7
  • 18