Cannot delete the database because it is currently in use
Copyright: This is an original post by the blogger and may not be reproduced without the blogger's permission. https://blog.csdn.net/huyuyang6688/article/details/43675371
This error was reported today when deleting a database in SQL Server, and I found a piece of code online that fixes the problem:.
Create a new query, execute the code below, perfect solution! (PS: Remember to change the "databasename" below to the name of the database to be deleted)
USE MASTER GO DECLARE @dbname SYSNAME SET @dbname = 'databasename' -- This is the name of the database library to be deleted DECLARE @s NVARCHAR(1000) DECLARE tb CURSOR LOCAL FOR SELECT s = 'kill ' + CAST(spid AS VARCHAR) FROM MASTER..sysprocesses WHERE dbid = DB_ID(@dbname) OPEN tb FETCH NEXT FROM tb INTO @s WHILE @@fetch_status = 0 BEGIN EXEC (@s) FETCH NEXT FROM tb INTO @s END CLOSE tb DEALLOCATE tb EXEC ('drop database [' + @dbname + ']')