Change logical database name with SMO
Asked Answered
L

3

9

How can I change the logical database name when restoring a database with SMO?

/Viktor

Linebreeding answered 20/2, 2010 at 5:50 Comment(1)
Do you mean the database name, or the filenames? All the answers below appear to assume you mean the logical file names?Vestpocket
B
5

You can't rename the logical database files with a SQL RESTORE DATABASE: it's not offered. Only physical files can be changed using WITH MOVE

You rename logical files by using ALTER DATABASE in SQL, normally.

This appears to be be confirmed by the RelocateFile SMO class.

Bread answered 20/2, 2010 at 10:15 Comment(0)
B
12
//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");
Bodleian answered 19/8, 2010 at 9:16 Comment(0)
B
5

You can't rename the logical database files with a SQL RESTORE DATABASE: it's not offered. Only physical files can be changed using WITH MOVE

You rename logical files by using ALTER DATABASE in SQL, normally.

This appears to be be confirmed by the RelocateFile SMO class.

Bread answered 20/2, 2010 at 10:15 Comment(0)
P
0

Rahul's code is correct: Restoring to new physical files and renaming logical files is a two-step process:

The RelocateFile call is saying "map this logical file name to this physical file". You need to use the logical file names of the original backup here NOT new ones, otherwise you are likely to get ".mdf cannot be overwritten" exceptions.

To make new logical names, use the Rename() calls afterwards, as shown in Rahul's code.

However, if you want to change the name of the database using 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();
Palladio answered 28/3, 2012 at 13:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.