我正在尝试使用以下c#代码将sql server .bak恢复为空数据库:
string dbBakFile = GetBackFileFromZip(restoreConfig.TmpUnZipFolder,restoreConfig.DatabaseFileToRestore);
if (string.IsNullOrEmpty(dbBakFile))
{
response.Status = DatabaseResponseStatus.Error;
response.Message = "No .bak file found in " + restoreConfig.DatabaseToRestore;
return response;
}
var builder =
new SqlConnectionStringBuilder(
ConfigurationManager.ConnectionStrings["myserver"].ConnectionString);
var smoServer =
new Server(new ServerConnection(builder.DataSource,builder.UserID,builder.Password));
var db = smoServer.Databases[restoreConfig.DatabaseToRestore];
if (db != null)
{
smoServer.KillAllProcesses(restoreConfig.DatabaseToRestore);
log.Debug("all processes on db killed");
}
string dbPath = Path.Combine(db.PrimaryFilePath, restoreConfig.DatabaseToRestore + ".mdf");
log.Debug("db path is " +dbPath);
string logPath = Path.Combine(db.PrimaryFilePath,restoreConfig.DatabaseToRestore + "_Log.ldf");
log.Debug("log path is " + logPath);
var restore = new Restore();
var deviceItem =
new BackupDeviceItem(dbBakFile, DeviceType.File);
restore.DatabaseFiles.Add(dbPath);
restore.DatabaseFiles.Add(logPath);
restore.Devices.Add(deviceItem);
restore.Database = restoreConfig.DatabaseToRestore;
restore.FileNumber = 1;
restore.Action = RestoreActionType.Files;
restore.ReplaceDatabase = true;
restore.PercentCompleteNotification = 10;
restore.PercentComplete +=restore_PercentComplete;
restore.Complete += restore_Complete;
restore.SqlRestore(smoServer);
db = smoServer.Databases[restoreConfig.DatabaseToRestore];
db.SetOnline();
smoServer.Refresh();
db.Refresh();
我收到以下错误:
Microsoft.SqlServer.Management.Smo.FailedOperationException: Restore failed for Server 'IM-M4500\SQLEXPRESS'. ---> Microsoft.SqlServer.Management.Smo.SmoException: System.Data.SqlClient.SqlError: The backup set holds a backup of a database other than the existing 'new-test-44444' database
是的,它确实包含不同的备份,我想覆盖并替换它也想将mdf和日志文件移动到新文件。我在恢复选项中遗漏了什么吗?
非常感谢
伊斯梅尔
答案 0 :(得分:1)
好的修复了我需要给它的当前db逻辑文件名的问题,我实际上正在做的是给它新的db逻辑文件名,所以
//get the logical file names
DataTable dtFileList = restore.ReadFileList(smoServer);
string dbLogicalName = dtFileList.Rows[0][0].ToString();
string logLogicalName = dtFileList.Rows[1][0].ToString();
restore.RelocateFiles.Add(GetRelocateFile(dbLogicalName, dbPath));
restore.RelocateFiles.Add(GetRelocateFile(logLogicalName, logPath));
这很好用。
答案 1 :(得分:0)
不要创建新数据库并尝试在其上进行恢复。而是使用以下查询。
RESTORE DATABASE dbname from disk='location' WITH MOVE 'data' TO 'name.mdf' MOVE '_Log' TO 'name_log.ldf'
要替换现有数据库,请将其名称放在dbname上,并在查询上使用WITH REPLACE