备注 | 修改日期 | 修改人 |
格式调整 | 2020-04-16 12:38:45[当前版本] | 系统管理员 |
其他原因...增加批处理命令 | 2020-03-17 16:12:17 | 系统管理员 |
CREAT | 2020-02-27 20:29:58 | 系统管理员 |
Sql server还原失败(数据库正在使用,无法获得对数据库的独占访问权)
问题分析:数据库还原的时候还有其他进程连在上面,导致无法获得独占造成的。
解决方案:
一、切断连接进程
1.查询要还原的数据库ID
Select *
from master..sysdatabases where name = '';
2.获取该数据库的进程
Select * from sys.sysprocesses a where a.dbid
= '';
3.杀掉连接在上面的进程
kill @spid;
此时去还原一般就可以了
批处理命令:
DECLARE @databasename VARCHAR(50)
DECLARE @dbid INT,@idcount
INT,@i INT,@spid INT
set @databasename=databasename
--输入数据库名称
Select @dbid=dbid from master..sysdatabases where name
= @databasename
Select @idcount=count(*) from sys.sysprocesses a
where a.dbid = @dbid
Select IDENTITY(int,1,1) as id,spid into
#spidtmp from sys.sysprocesses a where a.dbid = @dbid
set
@i=1
WHILE @i<=20
BEGIN
Select @spid=spid from #spidtmp where
id=@i
exec('kill '+@spid)
set @i+=1
END
二、
将当前需要还原的数据进行OFFLINE,还原后,再将该数据库ONLINE。
脚本如下,先运行第一脚本,还原成功后,运行第二脚本。
1)ALTER DATABASE [datebase] SET OFFLINE WITH ROLLBACK
IMMEDIATE
2)ALTER DATABASE [datebase] SET ONLINE WITH
ROLLBACK IMMEDIATE
如果此时还原还是不行。可能是删完进程马上有新的进程连进来,
导致一直失败。应用程序一直不停的进行数据库链接。
这时,可以在单用户下还原。
三、删完进程马上有新的进程连进来,导致一直失败。
单用户模式
单用户模式设置:
右键点击数据库 -> 属性 -> 选项 -> 状态 -> 限制访问(MULTI_USER 默认)
-> 选择Single-> 确定。然后还原。
或 GUI的模式,语句的办法比较简单
USE MASTER
GO
ALTER DATABASE 数据库名字 SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
设置单用户数据库必须要超级用户
四、
--
首先定位到master数据库
use master
go
declare
@dbname varchar(20)
set @dbname='dbtest' ---这是数据库名称
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