当我们在删除一个DB的时候,如果这个DB当前有其它应用程序正在使用,删除就会失败,如果是在SSMS中执行删除操作,可以将"Close existing connections"选项勾上再执行删除操作,如果是通过脚本来删除,就需要如下操作了:
1.先找到连接该DB的所有会话ID,
2.根据会话ID将所有会话强行关闭。
这里分享一段小脚本,可以将指定DB的所有会话一次性全部Kill掉:
USE Master
GO
DECLARE @DBName nvarchar(200)
SET @DBName = 'DB_Name' -- SET DB Name
IF OBJECT_ID('tempdb..#SessionList') IS NOT NULL
DROP TABLE #SessionList
CREATE TABLE #SessionList
(
spid bigint,
ecid int,
status nvarchar(100),
loginname nvarchar(100),
hostname nvarchar(200),
blk int,
dbname nvarchar(200),
cmd nvarchar(200),
request_id int
)
INSERT INTO #SessionList
EXEC sp_who
DECLARE @Count int
DECLARE @i int
SET @Count = (SELECT COUNT(*) FROM #SessionList WHERE dbname = @DBName)
SET @i = 0
WHILE @i < @Count
BEGIN
DECLARE @SQLString nvarchar(max)
DECLARE @Spid bigint
SET @Spid = (SELECT TOP (1) spid FROM #SessionList WHERE dbname = @DBName ORDER BY spid ASC)
SET @SQLString = 'kill '+ Convert(nvarchar(30),@Spid)
PRINT @SQLString
EXECUTE (@SQLString)
DELETE #SessionList WHERE spid = @Spid
SET @i = @i + 1
END
DROP TABLE #SessionList