sql2008 还原时 出现sqlserver数据库正在使用,所以无法获得对数据库的独占访问权

执行以下脚本,即可解决。

declare @dbname varchar(20)
set @dbname='hichina_hmp'  --这里给变量赋的值是要进行还原的数据库的名称

declare @sql nvarchar(500)
declare @spid int  --SPID sqlserver进程ID int
set @sql='declare getspid cursor for
select spid from sysprocesses  where dbid=db_id('''+@dbname+''')'--当前正由进程使用的数据库id  int
exec (@sql)
open getspid
fetch next from getspid into @spid
while @@fetch_status<>-1  --如果FETCH 语句没有执行失败或此行不在结果集中。
begin
exec('kill '+@spid)  --终止正常连接
fetch next from getspid into @spid
end
close getspid
deallocate getspid

原文地址:https://www.cnblogs.com/suneryong/p/2591212.html