Cannot drop database because it is currently in use

后端 未结 17 1368
北恋
北恋 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:25

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

    In SQL Server Management Studio 2016, perform the following:

    • Right click on database

    • Click delete

    • Check close existing connections

    • Perform delete operation

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

    before dropping a database, you drop the connection to that 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)
    
    0 讨论(0)
  • 2020-12-07 12:32

    For SQL server mgmt. studio:

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

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

    Go to available databases section and select master. Then Try DROP DATABASE the_DB_name.

    0 讨论(0)
  • 2020-12-07 12:39
    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 讨论(0)
提交回复
热议问题