When Asp.net is used to restore the backup database file, the following error may occur:
[Because the database is in use, it cannot obtain access to the database. The restore database operation is terminated abnormally. Changed the database context to 'master'.]
At this time, you are free to wait for other processes to release the corresponding permissions to restore success! Is there a solution? I have updated and solved the problem by referring to [Java.
[SQL code]
Reference content is as follows: -- When the database is being restored, the database will not be restored because it has been stored in the msater database. Exec killspid 'dbname' ends the process of the database so that the database can be restored. Create proc killspid (@ dbname varchar (20 )) As Begin Declare @ SQL nvarchar (500) Declare @ spid int Set @ SQL = 'Clare getspid cursor for select spid from sysprocesses where dbid = db_id (''' + @ dbname + ''')' Exec (@ SQL) Open getspid Fetch next from getspid into @ spid While @ fetch_status <>-1 Begin Exec ('Kill '+ @ spid) Fetch next from getspid into @ spid End Close getspid Deallocate getspid End |
[C # code]
Reference content is as follows: /// <Summary> /// Restore the database. You can choose whether to force restore the database (that is, when others are using the database, the database can still be restored) /// </Summary> /// <Param name = "databasename"> name of the database to be restored </param> /// <Param name = "databasefile"> full path of the backup file with restoration </param> /// <Param name = "errormessage"> information about database restoration failures </param> /// <Param name = "forceRestore"> whether to force restore (recovery). If it is TRUE, exec killspid 'database name' ends the process of the database, in this way, the database can be restored </param> /// <Returns> </returns> Public bool RestoreDataBase (string databasename, string databasefile, ref string errormessage, bool forceRestore) { Bool success = true; String path = databasefile; String dbname = databasename;
String restoreSql = "use master ;";
If (forceRestore) // if forced reply RestoreSql + = string. Format ("use master exec killspid '{0}';", databasename );
RestoreSql + = "restore database @ dbname from disk = @ path ;";
SqlCommand myCommand = new SqlCommand (restoreSql, conn );
MyCommand. Parameters. Add ("@ dbname", SqlDbType. Char ); MyCommand. Parameters ["@ dbname"]. Value = dbname; MyCommand. Parameters. Add ("@ path", SqlDbType. Char ); MyCommand. Parameters ["@ path"]. Value = path;
Try { MyCommand. Connection. Open (); MyCommand. ExecuteNonQuery (); } Catch (Exception ex) { Errormessage = ex. Message; Success = false; } Finally { MyCommand. Connection. Close (); }
Return success; } |