教程集 www.jiaochengji.com
教程集 >  数据库  >  mssql  >  正文 数据库还原时提示数据库正在使用的解决办法

数据库还原时提示数据库正在使用的解决办法

发布时间:2014-07-20   编辑:jiaochengji.com
数据库还原时提示数据库正在使用的解决办法

经常遇到这样的问题:想还原数据库的时候发现有程序在使用该数据库导致无法还原。
可以使用以下办法解决:
需要有master数据库的执行权限,执行以下sql语句
declare @dbname varchar
set @dbname=''testdb'' -------这里设置对应的数据库名
declare @sql nvarchar(500)
declare @spid int
set @sql=''declare getspid cursor for
select spid from sysprocesses where dbid=db_id(''''''+@dbname+'''''')''
exec (@sql)
open getspid
fetch next from getspid into @spid
while @@fetch_status<>-1
begin
exec(''kill ''+@spid)
fetch next from getspid into @spid
end
close getspid
deallocate getspid

还原数据库出错的处理:
在还原数据库时,有时会提示因为数据库正在使用,所以无法获得对数据库的独占访问权!!
这时需要在还原数据库前先杀死正在使用数据库得线程.

举例,杀死正在使用'testdb'数据库的线程:

declare @dbname varchar(20)
set @dbname='testdb'

declare @sql nvarchar(500)
declare @spid int   --SPID 值是当用户进行连接时指派给该连接的一个唯一的整数
set @sql='declare getspid cursor for
select spid from sysprocesses where dbid=db_id('''+@dbname+''')'
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

在写生产环境中的数据库还原脚本时,经常用到以上代码,共享给大家,希望对您有所帮助。

您可能感兴趣的文章:
数据库还原时提示数据库正在使用的解决办法
mysql备份还原后中文乱码的解决办法
asp.net连接数据库超时的解决办法
PHP连接数据库失败的原因是什么?
MariaDB与MySQL数据库之间有什么区别
数据库链接资源该怎么优化
使用存储过程sp_dbcmptlevel对SQL Server 2005调整兼容级别
mysql数据库表损坏的解决办法
ASP[Microsoft][ODBC Microsoft Access Driver] 不能更新 数据库或对象为只读
PHPMyAdmin编辑数据库表一直提示”正在加载”问题

[关闭]
~ ~