无法还原SQL Server数据库

时间:2018-02-01 16:25:53

标签: c# sql-server

我正在使用C#Windows窗体还原SQL Server数据库,并发生以下错误:

  

还原无法处理数据库'book_store',因为此会话正在使用它。建议在执行此操作时使用master数据库。正在回滚还原DATABASE终止异常非限定事务。预计回滚完成率:100%。

代码:

String sql = "ALTER DATABASE Book_store SET SINGLE_USER WITH ROLLBACK IMMEDIATE";
sql += "RESTORE DATABASE Book_store FROM DISK = '" + textboxpath.text + "' WITH REPLACE, STATES = 5";

SqlCommand cmd = new SqlCommand(sql,con);
cmd.ExecuteNonQuery();

2 个答案:

答案 0 :(得分:0)

您已连接到您尝试设置为单个用户的数据库。试试这个。

String sql = “USE master; ALTER DATABASE Book_store SET SINGLE_USER WITH ROLLBACK IMMEDIATE”;

答案 1 :(得分:0)

请使用以下代码恢复数据库:

using (sqlcon)
               {
                   string UseMaster = "USE master";
                   OdbcCommand UseMasterCommand = new OdbcCommand(UseMaster, sqlcon);
                   UseMasterCommand.ExecuteNonQuery();
                   // The below query will rollback any transaction which is
                   running on that database and brings SQL Server database in a single user mode.
                   string Alter1 = @"ALTER DATABASE
                   [" + DatabaseFullPath + "] SET Single_User WITH Rollback Immediate";
                   OdbcCommand Alter1Cmd = new OdbcCommand(Alter1, sqlcon);
                   Alter1Cmd.ExecuteNonQuery();
                   // The below query will restore database file from disk where backup was taken ....
                   string Restore = @"RESTORE DATABASE
                   [" + DatabaseFullPath + "] FROM DISK = N'" +
                   backUpPath + @"' WITH  FILE = 1,  NOUNLOAD,  STATS = 10";
                   OdbcCommand RestoreCmd = new OdbcCommand(Restore, sqlcon);
                   RestoreCmd.ExecuteNonQuery();
                   // the below query change the database back to multiuser
                   string Alter2 = @"ALTER DATABASE
                   [" + DatabaseFullPath + "] SET Multi_User";
                   OdbcCommand Alter2Cmd = new OdbcCommand(Alter2, sqlcon);
                   Alter2Cmd.ExecuteNonQuery();
                   Cursor.Current = Cursors.Default;
               }