“無法刪除資料庫,因為該資料庫當前正在使用” – 解決方法

cutdragonhit發表於2018-09-22

USE MASTER
GO

DECLARE @dbname SYSNAME
SET @dbname = `databasename` –這個是要刪除的資料庫庫名

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 + `]`)

相關文章