1

我正在使用 C# 代码还原 SQL 数据库。当我们使用 SQL Server Management Studio 还原备份时,我们可以选择备份集。我们可以使用代码来执行此操作吗? 在此处输入图像描述

我使用了以下代码

openFileDialog1.ShowDialog();
    string databaseName = "TempDb";
    Restore sqlRestore = new Restore();

    BackupDeviceItem deviceItem = new BackupDeviceItem(openFileDialog1.FileName, DeviceType.File);
    sqlRestore.Devices.Add(deviceItem);
    sqlRestore.Database = databaseName;

    DataConnection dataConnection = new DataConnection();
    ServerConnection connection = new ServerConnection(dataConnection.DataBaseConnection);
    Server sqlServer = new Server(connection);

    Database db = sqlServer.Databases[databaseName];
    sqlRestore.Action = RestoreActionType.Database;
    String dataFileLocation = db.FileGroups[0].Files[0].FileName;
    String logFileLocation = db.LogFiles[0].FileName;
    db = sqlServer.Databases[databaseName];
    sqlServer.ConnectionContext.Disconnect();
    RelocateFile rf = new RelocateFile(databaseName, dataFileLocation);


    sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName, dataFileLocation));
    sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName + "_log", logFileLocation));
    sqlRestore.ReplaceDatabase = true;
    sqlRestore.Complete += new ServerMessageEventHandler(sqlRestore_Complete);
    sqlRestore.PercentCompleteNotification = 10;
    sqlRestore.PercentComplete += new PercentCompleteEventHandler(sqlRestore_PercentComplete);
    sqlRestore.SqlRestore(sqlServer);
    db = sqlServer.Databases[databaseName];
    db.SetOnline();
    sqlServer.Refresh();

使用上面的代码它只恢复第一组。

4

1 回答 1

1

看一下Use all backup sets to restore database with SMO,看来

重要的字段是恢复对象上的 FileNumber。默认值为 1

您可以使用Restore.ReadBackupHeader方法获取备份集列表。

链接中的VB代码

res.Devices.AddDevice("C:\AdventureWorks2012Backup.BAK", DeviceType.File)
dt = res.ReadBackupHeader(srv)

For Each r As DataRow In dt.Rows
   For Each c As DataColumn In dt.Columns
      Console.WriteLine(c.ToString + " = " + r(c).ToString())
   Next
Next

所以一旦你知道你想要哪个备份集,你就可以设置

sqlRestore.FileNumber = YOUR_CHOSEN_SET;
于 2012-05-18T14:09:24.473 回答