选择带有最新时间戳的.bak文件

时间:2012-07-02 01:51:47

标签: sql-server database backup restore

我想将数据库备份文件.bak恢复到服务器,但是有一些带有不同时间戳的.bak文件,例如:

  

dbname_backup_201210290200.bak
  dbname_backup_201210300212.bak
  dbname_backup_201210310213.bak

1 个答案:

答案 0 :(得分:4)

假设启用了xp_cmdshell并且所有文件都以yyyyMMddhhmm.bak结尾:

CREATE TABLE #x(n VARCHAR(2048));

DECLARE @cmd VARCHAR(2048), @fn VARCHAR(2048), @folder VARCHAR(255);

SET @folder = 'E:\sqlbackup\MerchantAPIReport\'; --'
SET @cmd = 'dir /b "' + @folder + 'MerchantAPIReport_backup_*.bak"';

INSERT #x EXEC master..xp_cmdshell @cmd;

SELECT TOP (1) @fn = @folder + n 
  FROM #x
  ORDER BY CONVERT(DATETIME, 
    STUFF(STUFF(LEFT(RIGHT(n, 16), 12), 11, 0, ':'), 9, 0, ' '))
  DESC;

-- whatever you do, don't try to construct this yourself.
-- I'll fill in the blanks for you. <sigh>

RESTORE DATABASE [MerchantAPIReport] FROM DISK = @fn
  WITH FILE = 1,
  MOVE N'MerchantAPIReport'     TO N'D:\SQLData01\MerchantAPIReport.mdf',
  MOVE N'MerchantAPIReport_log' TO N'F:\SQLLog\MerchantAPIReport.ldf',
  NOUNLOAD, REPLACE, STATS = 10;

-- RESTORE DATABASE ... FROM @fn ...; -- fill in the rest here

DROP TABLE #x;