在还原数据库时,有时会出现“因为数据库正在使用,所以无法获得对数据库的独占访问权”的错误,这时就需要在还原数据库前先杀死正在使用数据库的线程。

---需要定位到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

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/cnkiminzhuhu/archive/2009/10/23/4717093.aspx

相关文章:

  • 2022-02-10
  • 2021-05-31
  • 2022-12-23
  • 2022-02-07
  • 2021-12-01
  • 2021-12-04
  • 2021-09-13
猜你喜欢
  • 2021-12-26
  • 2022-12-23
相关资源
相似解决方案