How to force a drop of MSSQL Server database

Sometimes IntelliSense and/or Management Studio will hang connections open just because you clicked on the database in Object Explorer. Also, if you have any SQL Agent jobs that access the database, these will not be stopped by disabling TCP/IP.

Regardless, the following script will "take over" the database by putting it into single-user mode in the session, and then take it offline so no one can connect to it to run queries.

You can then drop the database using Management Studio or T-SQL.

USE [MyDB];
GO

ALTER DATABASE [MyDB] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO

ALTER DATABASE [MyDB] SET OFFLINE;
GO

From http://www.morgantechspace.com/2013/11/Cannot-drop-database-because-it-is-currently-in-use-in-MS-SQL-Server.html

USE [master]
GO
ALTER DATABASE [TestDB] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
USE [master]
GO
/****** Object:  Database [TestDB]    Script Date: 11/29/2013 13:40:36 ******/
DROP DATABASE [TestDB]
GO

In C#

public static void DeleteDataBase()
{
    using (SqlConnection sqlconnection = new
        SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=master;Integrated Security=SSPI;"))
    {
        sqlconnection.Open();
        // if you used master db as Initial Catalog, there is no need to change database
        sqlconnection.ChangeDatabase("master");

        string rollbackCommand = @"ALTER DATABASE [TestDB] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE";

        SqlCommand deletecommand = new SqlCommand(rollbackCommand, sqlconnection);

        deletecommand.ExecuteNonQuery();

        string deleteCommand = @"DROP DATABASE [TestDB]";

        deletecommand = new SqlCommand(deleteCommand, sqlconnection);

        deletecommand.ExecuteNonQuery();
    }
}