views:

628

answers:

1

I am trying to restore a database by first restoring a full backup and then restoring a differential backup by using the Microsoft.SqlServer.Management.Smo.Restore class. The full backup is restored with the following code:

Restore myFullRestore = new Restore();
myFullRestore.Database = "DatabaseName";
myFullRestore.Action = RestoreActionType.Database;
myFullRestore.AddDevice(@"C:\BackupFile.bak", DeviceType.File);
myFullRestore.FileNumber = 1;
myFullRestore.SqlRestore(myServer); // myServer is an already-existing instance of Microsoft.SqlServer.Management.Smo.Server

After restoring the full backup (which completes successfully), my code for restoring the differential backup is as follows:

Restore myDiffRestore = new Restore();
myDiffRestore.Database = "DatabaseName";
myDiffRestore.Action = RestoreActionType.Database;
myDiffRestore.AddDevice(@"C:\BackupFile.bak", DeviceType.File);
myDiffRestore.FileNumber = 4; // file contains multiple backup sets, this is the index of the set I want to use
myDiffRestore.SqlRestore(myServer);

However, this code will throw a Microsoft.SqlServer.Management.Smo.FailedOperationException, with the message "Restore failed for server 'servername'". Do I need to explicitly state that I am restoring a differential backup, and if so, how do I go about doing this? Or is the problem less obvious than this? Any suggestions as to what I am doing wrong (or neglecting to do) would be greatly appreciated.

+2  A: 

After a little bit more digging I figured this one out. In order for the differential backup restore to work, the full restore needs to be performed with NoRecovery set to true:

// before executing the SqlRestore command for myFullRestore...
myFullRestore.NoRecovery = true;

This specifies that another transaction log needs to be applied, which in this case is the differential backup. This page has some more information that I found useful: http://doc.ddart.net/mssql/sql70/ra-rz_9.htm

Donut
Restoring with NoRecovery = true will leave the database in a "Restoring" state. To make it usable again use this command: RESTORE DATABASE <database name> WITH RECOVERY
James