备份数据库有很多种方式,我们选择的方案是完整备份+日志备份,等将来数据库大了以后,将变为完整备份+差异备份+日志备份,如图:
每天晚上进行数据库的完整备份,每30分钟进行日志备份,每次日志备份后系统会自动截断日志文件,这也能有效保证日志文件不会无限的增大。
--完整备份数据库 declare @toPath nvarchar(100) set @toPath = 'D:akTest_' + REPLACE(convert(nvarchar,GETDATE(),20),':','.') + '.bak' backup database Test to disk = @toPath with COMPRESSION,password = '123' --备份事务日志 declare @toLogPath nvarchar(100) set @toLogPath = 'D:akTest_log_' + REPLACE(convert(nvarchar,GETDATE(),20),':','.') + '.bak' BACKUP LOG Test To disk= @toLogPath --备份尾事务日志(在数据库出现故障时,备份最后的日志) BACKUP LOG Test To disk= @toLogPath with norecovery
--还原数据库 RESTORE DATABASE Test FROM DISK = 'D:akTest_2015-09-13 07.15.53.bak' with norecovery,password = '123', MOVE N'OA' TO N'D:dbTest.mdf', MOVE N'OA_log' TO N'D:dbTest.ldf' --还原事务日志(中间日志) RESTORE log Test FROM DISK = 'D:akTest_log2015-09-13 07.16.47.bak' with norecovery --还原事务日志(最后日志) RESTORE log Test FROM DISK = 'D:akTest_log2015-09-13 07.17.00.bak' WITH recovery --用stopat恢复尾日志备份 RESTORE log [Test] FROM DISK = 'D:akTest_2015-07-19 19.07.40.bak' WITH FILE = 3,stopat = '',recovery --根据备份文件获取数据库逻辑文件名 RESTORE FILELISTONLY FROM DISK = 'D:akTest_2015-09-13 07.15.53.bak' with password = '123'