我正在尝试使用 C# 代码恢复 sql 数据库。备份工作正常。但是当恢复数据库时,它给了我一个错误。我正在使用Microsoft.SqlServer.Management.Smo;
这个操作。错误为{“System.Data.SqlClient.SqlError: RESTORE cannot process database 'TempDb' because it is in this session. 建议执行此操作时使用主数据库。”}
在几篇文章中,它说将数据库设置为主数据库。我也试过了。但它给了我同样的错误。连接字符串:connectionString = @"server=(local);初始目录=Master;Integrated Security=True;";
我的代码如下:
openFileDialog1.ShowDialog();
string databaseName = "TempDb";
Restore sqlRestore = new Restore();
BackupDeviceItem deviceItem = new BackupDeviceItem(openFileDialog1.FileName, DeviceType.File);
sqlRestore.Devices.Add(deviceItem);
sqlRestore.Database = databaseName;
DataConnection dataConnection = new DataConnection();
ServerConnection connection = new ServerConnection(dataConnection.DataBaseConnection);
Server sqlServer = new Server(connection);
Database db = sqlServer.Databases[databaseName];
sqlRestore.Action = RestoreActionType.Database;
String dataFileLocation = db.FileGroups[0].Files[0].FileName;
String logFileLocation = db.LogFiles[0].FileName;
db = sqlServer.Databases[databaseName];
RelocateFile rf = new RelocateFile(databaseName, dataFileLocation);
sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName, dataFileLocation));
sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName + "_log", logFileLocation));
sqlRestore.ReplaceDatabase = true;
sqlRestore.Complete += new ServerMessageEventHandler(sqlRestore_Complete);
sqlRestore.PercentCompleteNotification = 10;
sqlRestore.PercentComplete += new PercentCompleteEventHandler(sqlRestore_PercentComplete);
sqlRestore.SqlRestore(sqlServer);
db = sqlServer.Databases[databaseName];
db.SetOnline();
sqlServer.Refresh();