如何将SQL Server数据库备份还原到新创建的数据库?

时间:2011-11-21 11:31:41

标签: sql-server-2005 smo database-restore

我有一个名为backupdb.bak的SQL Server 2005数据库备份。我想将其还原到数据库MyDatabase

但在恢复之前,我要检查MyDatabase是否已经存在。如果是,那么我创建一个名为MyDatabaseNew的新数据库,并将备份文件恢复到这个新数据库。

如果我直接将文件还原到MyDatabase,则该过程运行正常。但是,当我检查MyDatabase的存在并尝试创建名为MyDatabaseNew的新数据库时,它会给出错误:

  

服务器服务器名称

的还原失败

我的代码如下所示:

Restore restore = new Restore();
restore.Action = RestoreActionType.Database;
CreateDatabase(MyDatabaseNew);
restore.Database = MyDatabaseNew;
restore.ReplaceDatabase = true;

BackupDeviceItem deviceItem = new BackupDeviceItem("C:\\backupdb.bak",DeviceType.File);
restore.Devices.Add(deviceItem);
SqlConnection sqlCon = new SqlConnection("Data Source=.;Initial Catalog=MyDatabaseNewIntegrated Security=True;User ID=uid; Pwd=Pwd");
ServerConnection connection = new ServerConnection(sqlCon);
sqlCon.Open();

Microsoft.SqlServer.Management.Smo.Server smoServer = new Server(new  ServerConnection("."));
if (File.Exists("C:\\backupdb.bak"))
    // restore
    restore.SqlRestore(smoServer);
if (sqlCon.State == ConnectionState.Open)
    sqlCon.Close();

和我的create database(如果MyDatabase存在)代码如下所示,我将MyDatabaseNew作为此方法的参数传递:

public void CreateDatabase(string NewDBName)
{
  string str;
  SqlConnection myConn = new SqlConnection("Server=.;Integrated  security=True;
  database=master;User ID=uid;Password=Pwd");

  str = "CREATE DATABASE " + NewDBName + "";
  SqlCommand myCommand = new SqlCommand(str, myConn);
  try
  {
    myConn.Open();
    myCommand.ExecuteNonQuery();
    MessageBox.Show("New DataBase is Created Successfully", "Database Creation",
    MessageBoxButtons.OK, MessageBoxIcon.Information);
  }
  catch (System.Exception ex)
  {
    MessageBox.Show(ex.ToString(), "Database Creation", MessageBoxButtons.OK,
    MessageBoxIcon.Information);
  }
  finally
  {
    if (myConn.State == ConnectionState.Open)
    {
      myConn.Close();
    }
  }
}

任何人都可以告诉我哪里出错了吗?

1 个答案:

答案 0 :(得分:4)

恢复到新数据库时,需要使用等效的Transact-SQL's RESTORE DATABASE ... WITH MOVE ... statement来指定数据和日志文件的新名称:

restore.RelocateFiles.Add(new RelocateFile("MyDatabase", @"c:\MyDatabaseNew.mdf"));
restore.RelocateFiles.Add(new RelocateFile("MyDatabase_Log", @"c:\MyDatabaseNew.ldf"));

更多信息:Getting Started with SMO in SQL 2005 - Restores