Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving database name from bak file

I have a bak file that has in it a back up of a database .

I want to restore this database to a new location and I need to retrieve the database name from this file any idea how to do so ?

I need it to override the data file location and the log file location .

Thanks for help.

like image 490
Night Walker Avatar asked Nov 14 '10 09:11

Night Walker


1 Answers

RESTORE FILELISTONLY
FROM DISK = 'full path to your .bak file'

will show you the current file names in the backup. If there are multiple backups in one file and you do not specify "WITH FILE = X" you will only get information for the first backup in the file.

RESTORE DATABASE MyNewDBname
    FROM DISK = 'full path to your .bak file'
    WITH 
      MOVE 'LogicalFilename_Data' TO 'D:\somepath\...\MyDB.mdf',
      MOVE 'LogicalFilename_Log' TO 'D:\somepath\...\MyDB.ldf';
GO

Rough outline with SMO (not tested):

Restore restoreDB = new Restore();
restoreDB.Database = myDatabase.Name;
// Specify whether you want to restore database, files or log
restoreDB.Action = RestoreActionType.Database;
restoreDB.Devices.AddDevice(@"D:\somepath\...\MyDBFull.bak", DeviceType.File);

restoreDB.ReplaceDatabase = true; // will overwrite any existing DB     
restoreDB.NoRecovery = true;

// you can Wire up events for progress monitoring */
// restoreDB.PercentComplete += CompletionStatus;
// restoreDB.Complete += RestoreCompleted;

restoreDB.SqlRestore(myServer);

Ref.

Using SMO, you can retrieve the file list using Restore.ReadFileList

See Also: How to restore a database from C#

like image 148
Mitch Wheat Avatar answered Sep 19 '22 09:09

Mitch Wheat