如何在使用SMO还原数据库时更改逻辑数据库名称?
/尤
答案 0 :(得分:8)
//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");
答案 1 :(得分:4)
您无法使用SQL RESTORE DATABASE重命名逻辑数据库文件:它不是提供的。只能使用WITH MOVE
更改物理文件通常在SQL中使用ALTER DATABASE重命名逻辑文件。
这似乎是由RelocateFile SMO类确认的。
答案 2 :(得分:0)
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();