简体   繁体   English

无法将数据库还原到 SQL Server 中的快照

[英]Unable to restore database to a snapshot in SQL Server

I want to create a database snapshot and restore database to it every time a unit test is run.我想在每次运行单元测试时创建一个数据库快照并将数据库恢复到它。 I am able to create snapshot but while restoring it, I encounter the error below while doing it.我能够创建快照,但在恢复它时,我在执行时遇到以下错误。

Msg 5070, Level 16, State 2, Line 1消息 5070,级别 16,状态 2,第 1 行
Database state cannot be changed while other users are using the database 'ImportData'其他用户正在使用数据库“ImportData”时无法更改数据库状态

Msg 3013, Level 16, State 1, Line 1消息 3013,级别 16,状态 1,第 1 行
RESTORE DATABASE is terminating abnormally. RESTORE DATABASE 异常终止。

The SQL queries for creating and reverting database to snapshot are listed below.下面列出了用于创建和恢复数据库到快照的 SQL 查询。

Create snapshot:创建快照:

CREATE DATABASE Data_SShot
ON (NAME=Data,
    FILENAME='C:\Snapshot\DataSnapshot.ss'),
   (NAME=Data_Data1,
    FILENAME='C:\Snapshot\Data1Snapshot.ss'),
   (NAME=Data_Index1,
    FILENAME='C:\Snapshot\DataIndexSnapshot.ss')
AS SNAPSHOT OF Data

Restore to snapshot恢复到快照

use master
go

RESTORE DATABASE Data 
FROM DATABASE_SNAPSHOT = 'Data_SShot'

It states that它指出

Database state cannot be changed while other users are using the database当其他用户正在使用数据库时,不能更改数据库状态

How to overcome this problem?如何克服这个问题? I am using .NET (C#) to do this.我正在使用 .NET (C#) 来做到这一点。 How to close connection to run RESTORE DATABASE successfully?如何关闭连接以成功运行RESTORE DATABASE

I want this entire process of creating snapshot and reverting DB to it later to happen for each test in test suite.我希望创建快照并将数据库恢复到它的整个过程稍后发生在测试套件中的每个测试中。

There are few things which need to be done before restoring the DB. 在恢复数据库之前,需要做的事情很少。

  1. Get the number of active users for the DB and kill the sessions. 获取数据库的活动用户数并终止会话。
  2. Take the DB offline and online which will terminate all hidden connections. 使数据库脱机并在线,这将终止所有隐藏的连接。
  3. Now restore the DB. 现在恢复数据库。 If it fails, then take the DB offline and try to restore. 如果失败,则使数据库脱机并尝试恢复。
  4. Once restore is done, bring the DB online. 恢复完成后,将数据库联机。

These are the steps which I have been using for DB restore and it's worked for me for a long time. 这些是我一直用于数据库恢复的步骤,它对我来说已经很长时间了。

Do the following:请执行下列操作:

ALTER DATABASE [Data] SET SINGLE_USER

RESTORE DATABASE Data 
FROM DATABASE_SNAPSHOT = 'Data_SShot'

ALTER DATABASE [Data] SET MULTI_USER WITH NO_WAIT

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM