使用SMO从.bak文件还原数据库

时间:2013-09-18 21:12:54

标签: sql-server restore smo

我尝试了一些解决方案,下面是最直接的解决方案,但我得到了以下错误

  

逻辑文件'RestoredProcessMananger'不是数据库'RestoredProcessMananger'的一部分。使用RESTORE FILELISTONLY列出逻辑文件名。

     

RESTORE DATABASE正在异常终止。

我做错了什么?我的想法是创建DLL以供其他程序使用,允许在服务器上重新加载基线数据库,覆盖那里的任何内容。

   ServerConnection connection = new ServerConnection("xxx", "sa", "srv$xxx");
   Server svr =new Server(connection);
   Restore res = new Restore();
   res.Database = "RestoredProcessMananger";
   res.Action = RestoreActionType.Database;
   res.Devices.AddDevice(@"C:\temp\ProcessManager.bak", DeviceType.File);
   res.ReplaceDatabase = true;

   res.RelocateFiles.Add(new RelocateFile("RestoredProcessMananger", _
          @"c:\ProcessManager2.mdf"));
   res.RelocateFiles.Add(new RelocateFile("RestoredProcessMananger_Log", _
          @"c:\ProcessManager2_log.ldf"));

   res.SqlRestore(svr);
   svr.Refresh();

编辑1:修复

 public static void RestoreDatabase(string Server, //sqlserver //from CONFIG
        string BackupFilePath, //where the bak file I want to restore  //from CONFIG
        string destinationDatabaseName, //what the restored database will be called //from CONFIG
        string DatabaseFolder, //where the data/log files for the destination (break into 2 variables (2 different locations)) (get from GetDatabaseMDFFilePathName)
        string DatabaseFileName, //the destination MDF file name (get from GetDatabaseMDFFilePathName)
        string DatabaseLogFileName) //the destination LDF file name (get from GetDatabaseMDFFilePathName)
    {
        Server myServer = GetDatabases("xxx");
        Restore myRestore = new Restore();
        myRestore.Database = destinationDatabaseName;
        Database currentDb = myServer.Databases[destinationDatabaseName];
        if (currentDb != null)
            myServer.KillAllProcesses(destinationDatabaseName);
        myRestore.Devices.AddDevice(BackupFilePath, DeviceType.File);
        string DataFileLocation = DatabaseFolder + "\\" + destinationDatabaseName + ".mdf";
        string LogFileLocation = DatabaseFolder + "\\" + destinationDatabaseName + "_log.ldf";
        myRestore.RelocateFiles.Add(new RelocateFile(DatabaseFileName, DataFileLocation));
        myRestore.RelocateFiles.Add(new RelocateFile(DatabaseLogFileName, LogFileLocation));
        myRestore.ReplaceDatabase = true;
        myRestore.PercentCompleteNotification = 10;
        myRestore.SqlRestore(myServer);
        currentDb = myServer.Databases[destinationDatabaseName];
        currentDb.SetOnline();
    }

1 个答案:

答案 0 :(得分:2)

该错误表示RestoredProcessMananger不是备份文件中包含的逻辑文件的名称。

您是否使用RESTORE FILELISTONLY ...列出.BAK文件中包含的文件?

例如,如果您的备份文件名为C:\ MyBackupFile.bak,则需要从SQL Server Management Studio(或SQLCMD等)运行以下查询:

RESTORE FILELISTONLY FROM DISK='C:\MyBackupFile.bak';

这将提供备份文件中包含的逻辑文件的列表。然后,您需要将其中一个文件的名称传递到RelocateFile代码中。