2016-09-08 30 views
1
RESTORE DATABASE Status_backup_2015_05_31_230001_686899 
FROM DISK = 'E:\Restore\Status_backup_2015_05_31_230001_686899.bak' 
WITH FILE = 1, 
MOVE 'StatusBackup_Data' TO 'E:\Restore\Files\Status_backup_2015_05_31_230001_686899.mdf', 
MOVE 'StatusBackup_Log' TO 'E:\Restore\Files\Status_backup_2015_05_31_230001_686899.ldf', 
NOUNLOAD, REPLACE, STATS = 1 
GO 

我有下面的腳本來從備份恢復數據庫。還有另外9個帶日期戳的.bak文件如何添加.bak文件的循環來恢復單個腳本?

Status_backup_2015_10_31_230001_754565 
Status_backup_2015_09_31_230001_865643 
Status_backup_2015_08_31_230012_967686 
Status_backup_2015_07_31_230001_676760 
Status_backup_2015_06_31_230001_665455 
Status_backup_2015_04_31_230001_355656 
Status_backup_2015_03_31_230001_246754 
Status_backup_2015_02_31_230001_646457 
Status_backup_2015_01_31_230001_975644 

我需要將所有這些作爲循環放入上面的腳本中。我正在嘗試添加但沒有正確包含腳本。請任何人都可以建議我如何添加剩餘的.bak文件。

謝謝。

+0

爲所有其它的備份文件的日誌備份爲你需要申請相同的數據庫?或者它們應該是完整的備份,並且每個都將恢復到它自己的數據庫? –

+0

都是完全備份,每個都必須在自己的.mdf和.ldf文件中使用時間戳恢復到文件夾中。 – Amelia

回答

0

給這個基於光標的方法一試:

CREATE TABLE #restoreFiles(
backupfile VARCHAR(100)) 

INSERT INTO #restoreFiles (backupfile) 
VALUES ('Status_backup_2015_10_31_230001_754565'), 
     ('Status_backup_2015_09_31_230001_865643'), 
     ('Status_backup_2015_08_31_230012_967686'), 
     ('Status_backup_2015_07_31_230001_676760'), 
     ('Status_backup_2015_06_31_230001_665455'), 
     ('Status_backup_2015_04_31_230001_355656'), 
     ('Status_backup_2015_03_31_230001_246754'), 
     ('Status_backup_2015_02_31_230001_646457'), 
     ('Status_backup_2015_01_31_230001_975644') 

DECLARE @fileToRestore VARCHAR(100), @backupLocation varchar(500), @mdfLocation varchar(500), @ldfLocation varchar(500) 

DECLARE restorecursor CURSOR FOR 
SELECT backupfile FROM #restoreFiles 

OPEN restorecursor 

FETCH NEXT FROM restorecursor 
INTO @fileToRestore 

WHILE @@FETCH_STATUS = 0 
BEGIN 
    SET @backupLocation = 'E:\Restore\' + @fileToRestore + '\' + @fileToRestore +'.bak' 
    SET @mdfLocation = 'E:\Restore\Files\' + @fileToRestore + '.mdf' 
    SET @ldfLocation = 'E:\Restore\Files\' + @fileToRestore + '.ldf' 
    RESTORE DATABASE @fileToRestore 
    FROM DISK = @backupLocation 
    WITH FILE = 1, 
    MOVE 'StatusBackup_Data' TO @mdfLocation, 
    MOVE 'StatusBackup_Log' TO @ldfLocation, 
    NOUNLOAD, REPLACE, STATS = 1 

    FETCH NEXT FROM restorecursor 
    INTO @fileToRestore 
END 
CLOSE restorecursor 
DEALLOCATE restorecursor 
+0

對不起,我忘了添加。所有這些.bak文件都在它們自己的文件夾中。例如:Status_backup_2015_10_31_230001_754565.bak位於Status_backup_2015_10_31_230001_754565文件夾中,而Status_backup_2015_09_31_230001_865643位於Status_backup_2015_09_31_230001_865643文件夾中,依此類推。我仍然可以使用遊標使用上面的代碼嗎?請告訴我。 – Amelia

+0

剛剛更新了答案以符合新要求。 –

+0

謝謝。當我執行查詢時,我得到了以下錯誤:Msg 102,Level 15,State 1,Line 39 '+'附近的語法錯誤。 消息319,級別15,狀態1,行41 關鍵字'with'附近的語法不正確。如果此語句是公用表表達式,xmlnamespaces子句或更改跟蹤上下文子句,則前面的語句必須以分號結尾。 – Amelia

相關問題