-3

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

dbname_backup_201210290200.bak
dbname_backup_201210300212.bak
dbname_backup_201210310213.bak

4

1 回答 1

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;
于 2012-07-02T02:17:11.953 回答