I am sing C#, .NET 3.5, and SMO to create a copy of a database (our production database) to some other databases (our DEV and Test-database) in SQL Server 2005.
I have managed to create a backup from a database, an to restore it. this of course overwrites the existing one. I have used this CodeProject guide.
How do I restore a backup of a database into another database, with a different name on the same server?
using Microsoft.SqlServer.Management.Smo;
string backupFile="Backupfile";//.bak file
string dbName = "DBName";
string dbServerMachineName = "MachineName";
Microsoft.SqlServer.Management.Smo.Server server = new Microsoft.SqlServer.Management.Smo.Server(dbServerMachineName);
Database database = new Database(server, dbName);
//If Need
database.Create();
database.Refresh();
//Restoring
Restore restore = new Restore();
restore.NoRecovery = false;
restore.Action = RestoreActionType.Database;
BackupDeviceItem bdi = default(BackupDeviceItem);
bdi = new BackupDeviceItem(backupFile, DeviceType.File);
restore.Devices.Add(bdi);
restore.Database = dbName;
restore.ReplaceDatabase = true;
restore.PercentCompleteNotification = 10;
restore.SqlRestore(server);
database.Refresh();
database.SetOnline();
server.Refresh();
In short:
Restore.Database
property to a new name,Restore.ReplaceDatabase
property to true
,Restore.RelocateFiles
property.For a detailed explanation, read the Restoring a Database to a New Location section of the Getting Started with SMO in SQL 2005 - Restores article.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With