我试图创建数据库备份并恢复到另一个数据库,备份正在工作但恢复失败,原因是我在创建备份时创建的数据库名称也像 使用主 创建数据库[Samplename] 然后生成所有表数据 所以,当我尝试使用C#来恢复,它试图创建新的数据库为Samplename没有我的新SAMPLEDB,那么它给例外如何用新的数据库名称恢复Sqlserver .bak文件使用c#
The file 'C:\Program Files (x86)\Microsoft SQL
Server\MSSQL11.BIZSQL\MSSQL\DATA\Product Company.mdf' cannot be
overwritten. It is being used by database 'Sample Product Company'.
File 'Sample Product Company' cannot be restored to 'C:\Program Files
(x86)\Microsoft SQL Server\MSSQL11.BIZSQL\MSSQL\DATA\Sample Product
Company.mdf'. Use WITH MOVE to identify a valid location for the file.
The file 'C:\Program Files (x86)\Microsoft SQL
Server\MSSQL11.BIZSQL\MSSQL\DATA\Sample Product Company_log.ldf' cannot be overwritten.
It is being used by database 'Sample Product Company'.
File 'Sample Product Company_log' cannot be restored to 'C:\Program Files
(x86)\Microsoft SQL Server\MSSQL11.BIZSQL\MSSQL\DATA\Sample Product
Company_log.ldf'. Use WITH MOVE to identify a valid location for the file.
Problems were identified while planning for the RESTORE statement. Previous
messages provide details.
RESTORE DATABASE is terminating abnormally.
你可以请指导我如何恢复与新数据库的数据库中SQlser2012R2
示例代码还原:
using (SqlConnection con = new SqlConnection(ConnectionString))
{
con.Open();
string UseMaster = "USE master";
SqlCommand UseMasterCommand = new SqlCommand(UseMaster, con);
UseMasterCommand.ExecuteNonQuery();
int iReturn = 0;
// If the database does not exist then create it.
string strCommand = string.Format("SET NOCOUNT OFF; SELECT COUNT(*) FROM master.dbo.sysdatabases where name=\'{0}\'", DatabaseName);
using (SqlCommand sqlCmd = new SqlCommand(strCommand, con))
{
iReturn = Convert.ToInt32(sqlCmd.ExecuteScalar());
}
if (iReturn == 0)
{
SqlCommand command = con.CreateCommand();
command.CommandText = "CREATE DATABASE " + DatabaseName;
command.ExecuteNonQuery();
}
ServerConnection serverConnection = new ServerConnection(con);
Microsoft.SqlServer.Management.Smo.Server srv = new Microsoft.SqlServer.Management.Smo.Server(serverConnection);
string Alter1 = @"ALTER DATABASE [" + DatabaseName + "] SET Single_User WITH Rollback Immediate";
SqlCommand Alter1Cmd = new SqlCommand(Alter1, con);
Alter1Cmd.ExecuteNonQuery();
string Restore = @"RESTORE Database [" + DatabaseName + "] FROM DISK = N'" + fileName + @"' WITH FILE = 1, NOUNLOAD, REPLACE, STATS = 10";
SqlCommand RestoreCmd = new SqlCommand(Restore, con);
RestoreCmd.ExecuteNonQuery();
string Alter2 = @"ALTER DATABASE [" + DatabaseName + "] SET Multi_User";
SqlCommand Alter2Cmd = new SqlCommand(Alter2, con);
Alter2Cmd.ExecuteNonQuery();
}
我测试了你的代码,我没有收到任何异常,恢复成功。当你调试时,你对变量“fileName”有什么价值 – StackTrace
文件名是:RestoreBackup。我在另一台机器上创建备份并尝试在我的系统中恢复,然后它的工作正常,但是如果我在我的机器上创建和恢复它不工作..我的机器有Windows8.1和Sqlserver2012 R2和另一台机器有Windows7和Sqlserver2012R2 ..“ –