【问题标题】:Change logical database name with SMO使用 SMO 更改逻辑数据库名称
【发布时间】:2011-01-19 01:31:00
【问题描述】:

使用 SMO 恢复数据库时如何更改逻辑数据库名称?

/维克托

【问题讨论】:

  • 你是指数据库名还是文件名?以下所有答案似乎都假设您的意思是逻辑文件名?

标签: c# sql-server smo


【解决方案1】:
//restore is the Restore object in SMO

restore.RelocateFiles.Add(new RelocateFile(SourceDataFile.Name, Path.Combine(destinationDirectory, destination.Database + ".mdf")));
restore.RelocateFiles.Add(new RelocateFile(SourceLogFile.Name, Path.Combine(destinationDirectory, destination.Database + "_log.ldf")));

restore.SqlRestore(destinationServer);

var destinationDatabase = destinationServer.Databases[destinationDatabaseName];

//renaming the logical files does the trick

destinationDatabase.FileGroups[0].Files[0].Rename(destinationDatabaseName);
destinationDatabase.LogFiles[0].Rename(destinationDatabaseName + "_log");

【讨论】:

    【解决方案2】:

    您不能使用 SQL RESTORE DATABASE 重命名逻辑数据库文件:不提供。使用 WITH MOVE 只能更改物理文件

    您通常在 SQL 中使用 ALTER DATABASE 重命名逻辑文件。

    RelocateFile SMO 类似乎证实了这一点。

    【讨论】:

      【解决方案3】:

      Rahul 的代码是正确的:恢复到新的物理文件和重命名逻辑文件是一个两步过程:

      RelocateFile 调用是说“将此逻辑文件名映射到此物理文件”。您需要在这里使用原始备份的逻辑文件名而不是新的,否则您可能会得到“.mdf cannot be overwritten”异常。

      要创建新的逻辑名称,请在之后使用 Rename() 调用,如 Rahul 的代码所示。

      但是,如果您想使用 SMO 更改数据库的名称:

      var srvConn = new ServerConnection(serverName)     
      {  
          LoginSecure = false,  
          Login = dbUserName,  
          Password = dbUserPassword,  
          DatabaseName = "master",               
      };  
      var mainDb = new Database(srvConn, "old database name");  
      mainDb.Rename("new database name");
      mainDb.Refresh();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-13
        • 2013-11-17
        • 2022-01-26
        • 2011-02-21
        • 1970-01-01
        • 1970-01-01
        • 2017-12-07
        • 1970-01-01
        相关资源
        最近更新 更多