159

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.

0

21 Answers 21

163

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)
6
  • 3
    +1 I wonder why you did not get this earlier, this is a very handy answer. Thanks Mar 8, 2012 at 11:18
  • Won't that bring in non-user processes as well?
    – monksy
    Oct 8, 2013 at 22:27
  • For me I get the error "KILL command cannot be used inside user transactions."
    – Ally
    May 9, 2014 at 13:59
  • If the transaction is causing a problem, don't use the transaction. Dec 8, 2015 at 16:50
  • 1
    FYI, this seems to do what you said it would, but isn't solving the issue for me. Dec 8, 2015 at 16:51
143

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 :)

2
  • 2
    don't forget to add this at the begining use master go as well if you currently select [MyDatabase] Jun 20, 2019 at 6:29
  • 1
    @ThànhChungBùi what you pointed at solved my problem. It should be included in the answers. Thank you. Sep 8, 2020 at 13:14
84

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

4
  • 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, 2013 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, 2020 at 21:56
  • 1
    @AceAlfred Yours is the easiest one among all. Should have been one of the answers. Thanks.
    – Amit Ray
    Nov 27, 2020 at 6:08
  • 1
    After SP_WHO verify the Id and then use KILL id, like KILL 123 Nov 27 at 3:09
59

For SQL server mgmt. studio:

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

3
  • 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, 2016 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. Sep 8, 2020 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, 2021 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

36
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 !

0
10

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'
2
  • 1
    I dont think action deletes the database.
    – snp.it
    Mar 11, 2019 at 17:37
  • 2
    after detaching the database now it ready to be deleted with this query. DROP DATABASE dbname; Oct 14, 2019 at 7:51
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
1
  • I my case I had more than 1 connection to the DB I I wanted to drop.
    – AlexMelw
    Jun 15, 2017 at 5:10
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
4
  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
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.

1
  • 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 2, 2014 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

1
  • 1
    Idea with single user mode seems to be the cleanest way to do it.
    – Gucu112
    Jan 4, 2021 at 11:35
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]]]
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
1
  • 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 Aug 19, 2020 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);
        }
    }
5
  • 1
    The question needs a C# response, as it is tagged that way. Mar 25, 2014 at 20:30
  • @MathiasLykkegaardLorenzen there are several freeware apps that can translate .NET code across all languages. There even online apps. Aug 25, 2015 at 13:45
  • 1
    Point taken. I would have changed my vote, but I can't, as it is locked. Aug 25, 2015 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. Feb 21, 2017 at 8: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 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!

1
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.

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.

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
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.