Cannot drop database because it is currently in use

后端 未结 17 1370
北恋
北恋 2020-12-07 11:50

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

public void DropDataBase(string DBName,SqlConnection scon)
{
    try
    {
               


        
相关标签:
17条回答
  • 2020-12-07 12:39

    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
    
    0 讨论(0)
  • 2020-12-07 12:40

    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

    0 讨论(0)
  • 2020-12-07 12:40

    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'
    
    0 讨论(0)
  • 2020-12-07 12:40

    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]]]
    
    0 讨论(0)
  • 2020-12-07 12:41

    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.

    0 讨论(0)
  • 2020-12-07 12:41

    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 讨论(0)
提交回复
热议问题