删除数据库方法---用游标杀死进程再删除数据库

DECLARE @dbname SYSNAME
SET @dbname = ‘DemoDb’ --这个是要删除的数据库库名
/用游标杀死进程/
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 + ‘]’)

你可能感兴趣的:(删除数据库方法---用游标杀死进程再删除数据库)