在还原数据库时,有时会出现“因为数据库正在使用,所以无法获得对数据库的独占访问权”的错误,这时就需要在还原数据库前先杀死正在使用数据库的线程。
---需要定位到master 数据库
declare @dbname varchar(20)
set @dbname='Ucar' --这里给变量赋的值是要进行还原的数据库的名称
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
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/23109131/viewspace-714286/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/23109131/viewspace-714286/