SQL SERVER数据库批量日志还原生成脚本

在对SQL SERVER数据库进行异地恢复的过程中,很多时候,由于完整备份时间比较久远,或数据库事务日志的备份频率较高,如想把数据库恢复到最新的状态,需要进行多次的日志还原,这个时候手动操作比较繁琐,下面将用脚本方式将在源库批量生成还原脚本,可在异地一次性批量执行,比较方便灵活:

SELECT bs.database_name AS 'Database Name',
    bs.backup_start_date AS 'Backup Start',
    bs.backup_finish_date AS 'Backup Finished',
    DATEDIFF(MINUTE, bs.backup_start_date, bs.backup_finish_date) AS 'Duration (min)',
    'restore '+ 
    CASE bs.[type]   
        WHEN 'D' THEN 'database ' 
        else 'log ' 
    +bs.database_name +' from disk='''+ bmf.physical_device_name + ''' with norecovery;' AS 'Backup File',
        WHEN bs.[type] = 'D' THEN 'Full Backup'
        WHEN bs.[type] = 'I' THEN 'Differential Database'
        WHEN bs.[type] = 'L' THEN 'Log'
        WHEN bs.[type] = 'F' THEN 'File/Filegroup'
        WHEN bs.[type] = 'G' THEN 'Differential File'
        WHEN bs.[type] = 'P' THEN 'Partial'
        WHEN bs.[type] = 'Q' THEN 'Differential partial'
    END AS 'Backup Type'
FROM msdb.dbo.backupmediafamily bmf WITH(NOLOCK)
    INNER JOIN msdb..backupset bs WITH(NOLOCK)
    ON bmf.media_set_id = bs.media_set_id
WHERE bs.database_name = 'test'                         --请输入要还原的库名
and bs.backup_start_date>='2019-04-01 04:00:00.000'     --请输入要还原的起始时间
and bs.backup_finish_date <= '2019-09-01 18:16:03.000'  --请输入要还原的结束时间
ORDER BY bs.backup_start_date asc