如何自动从目录中恢复.bak文件名?

时间:2016-11-03 11:47:56

标签: sql-server

我使用下面的脚本来恢复我手动给出.bak文件名的数据库。我需要做自动化过程来恢复数据库。所以我尝试使用带有xp_DirTree的存储过程从远程服务器文件夹中获取.bak文件名。但存储过程执行没有结果。当我尝试本地路径时,我可以将.bak文件看到文件夹中。起初我认为这是许可问题,但权限很好。有谁能建议我造成什么错误?

用于恢复数据库的

脚本:

CREATE TABLE #CustomerrestoreFiles(
backupfile VARCHAR(100))
--Drop Table #CustomerrestoreFiles (backupfile)
VALUES  

('Customer_backup_2016_09_15_203001_9888161'),
('Customer_backup_2016_10_10_203001_7101588'),
('Customer_backup_2016_10_14_203001_6621303'),
('Customer_backup_2016_10_15_203001_5397847'),
('Customer_backup_2016_10_16_203002_0291343'),
('Customer_backup_2016_10_17_203002_2861353')


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

DECLARE restorecursor CURSOR FOR
SELECT backupfile FROM #CustomerrestoreFiles

OPEN restorecursor

FETCH NEXT FROM restorecursor
INTO @CustomerDBfileToRestore

WHILE @@FETCH_STATUS = 0
BEGIN
    SET @backupLocation = 'F:\Customer bak files' + '\' + @CustomerDBfileToRestore + '\' + @CustomerDBfileToRestore +'.bak'
    SET @mdfLocation = 'F:\Files\Customer_Restore_Files\' + @CustomerDBfileToRestore + '.mdf'
    SET @ldfLocation = 'F:\Files\Customer_Restore_Files\' + @CustomerDBfileToRestore + '.ldf'
    RESTORE DATABASE @CustomerDBfileToRestore
    FROM DISK = @backupLocation

    WITH  FILE = 1,

    MOVE 'Customer_Data' TO @mdfLocation,
        MOVE 'Customer_Log'  TO @ldfLocation,
    NOUNLOAD,  REPLACE,  STATS = 1

    FETCH NEXT FROM restorecursor
    INTO @CustomerDBfileToRestore
END
CLOSE restorecursor
DEALLOCATE restorecursor

1 个答案:

答案 0 :(得分:0)

我敢打赌这是映射网络驱动器问题。 sql用户无法看到驱动器。请尝试使用UNC命名。下面的文章可能有用。

How to backup a database to a network drive