Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change logical database name with SMO

Tags:

c#

sql-server

smo

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

/Viktor

like image 396
Viktor Avatar asked Feb 20 '10 05:02

Viktor


2 Answers

//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");
like image 76
Rahul Avatar answered Sep 28 '22 17:09

Rahul


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.

like image 37
gbn Avatar answered Sep 28 '22 18:09

gbn