我备份了一个数据库:
BACKUP DATABASE MyDatabase
TO DISK = 'MyDatabase.bak'
WITH INIT --overwrite existing
然后试图恢复它:
RESTORE DATABASE MyDatabase
FROM DISK = 'MyDatabase.bak'
WITH REPLACE --force restore over specified database
现在数据库处于还原状态。
有些人推测,这是因为备份中没有日志文件,需要使用以下方法前滚:
RESTORE DATABASE MyDatabase
WITH RECOVERY
当然,这是行不通的:
Msg 4333, Level 16, State 1, Line 1
The database cannot be recovered because the log was not restored.
Msg 3013, Level 16, State 1, Line 1
RESTORE DATABASE is terminating abnormally.
在灾难性的情况下,你想要的是一个无法工作的恢复。
备份包含数据文件和日志文件:
RESTORE FILELISTONLY
FROM DISK = 'MyDatabase.bak'
Logical Name PhysicalName
============= ===============
MyDatabase C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\MyDatabase.mdf
MyDatabase_log C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\MyDatabase_log.LDF
执行RESTORE DATABASE/RESTORE LOG命令时,默认使用WITH RECOVERY选项。如果你被困在“恢复”过程中,你可以通过执行以下命令将数据库恢复到在线状态:
RESTORE DATABASE YourDB WITH RECOVERY
GO
如果需要恢复多个文件,CLI命令分别需要WITH NORECOVERY和WITH RECOVERY -只有命令中的最后一个文件需要WITH RECOVERY才能使数据库恢复在线:
RESTORE DATABASE YourDB FROM DISK = 'Z:\YourDB.bak'
WITH NORECOVERY
GO
RESTORE LOG YourDB FROM DISK = 'Z:\YourDB.trn'
WITH RECOVERY
GO
你也可以使用SQL Server Management Studio向导:
也有虚拟恢复过程,但你必须使用第三方解决方案。通常,您可以使用数据库备份作为实时在线数据库。ApexSQL和Idera都有自己的解决方案。由SQL Hammer审查关于ApexSQL恢复。如果要处理大量备份,虚拟恢复是一个很好的解决方案。恢复过程要快得多,还可以节省磁盘驱动器上的大量空间。你可以看看这里的信息图进行一些比较。
如果您想从备份文件恢复SQL Server数据库,可以使用以下脚本:
RESTORE DATABASE [MyDatabase] -- which database to restore
FROM DISK = N'X:\MyDatabase.bak' -- location of the database backup
WITH
FILE = 1, -- restore from a backup file
-- declare where the file groups should be located (can be more than two)
MOVE N'MyDatabase_Data' TO N'D:\SSDPATH\MyDatabase.mdf',
MOVE N'MyDatabase_Log' TO N'E:\HDDPATH\MyDatabase.ldf',
-- Tape option; only relevant if you backup from magnetic tape
NOUNLOAD,
-- brings the database online after the database got restored
-- use this option when you don't want to restore incremental backups
-- use NORECOVERY when you want to restore differential and incremental backup files
RECOVERY,
-- replace existing database with the backup
-- deletes the existing database
REPLACE,
-- print log message for every 1 percent of restore
STATS = 1;