Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 555
sachin kulkarni Avatar asked Sep 19 '11 09:09

sachin kulkarni


People also ask

Can't drop a database because it is in use?

If you want to delete the database, you will get this error if there is an open session on the database. First, set the database to single_user mode. Then you can delete it.

How do I force drop a database in SQL Server?

To remove a database from the current server without deleting the files from the file system, use sp_detach_db. USE master; ALTER DATABASE [databasename] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [databasename] ; Note, database backups will not be deleted as part of the process documented above.


2 Answers

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) 
like image 104
unruledboy Avatar answered Sep 20 '22 15:09

unruledboy


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

like image 30
Hitesh Avatar answered Sep 17 '22 15:09

Hitesh