sachin kulkarni sachin kulkarni - 1 year ago 110
ASP.NET (C#) Question

Cannot drop database because it is currently in use

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.

Answer Source

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