I'm trying to restore a database from a .BAK
file using C# and SMO. This is my code.
public static void RestoreDatabase()
{
string dbConnString = Configuration.DatabaseConnectionString;
ServerConnection connection = new ServerConnection(@"dbserver\sqlexpress", "user", "password");
Server smoServer = new Server(connection);
Restore rstDatabase = new Restore();
rstDatabase.Action = RestoreActionType.Database;
rstDatabase.Database = "AppDb";
BackupDeviceItem bkpDevice = new BackupDeviceItem(@"TestData\db-backup.bak", DeviceType.File);
rstDatabase.Devices.Add(bkpDevice);
rstDatabase.ReplaceDatabase = true;
// Kill all processes
smoServer.KillAllProcesses(rstDatabase.Database);
// Set single-user mode
Database db = smoServer.Databases[rstDatabase.Database];
db.DatabaseOptions.UserAccess = DatabaseUserAccess.Single;
db.Alter(TerminationClause.RollbackTransactionsImmediately);
rstDatabase.SqlRestore(smoServer);
}
However when I try to run this method I get the following (error) message when it attempts to kill all processes:
Cannot use KILL to kill your own process.
I would be very grateful if someone could help solve this issue.
Right-click on a database in SSMS and choose delete. In the dialog, check the checkbox for "Close existing connections." Click the Script button at the top of the dialog.
After you have connected, right click on the instance name and select 'Activity Monitor' from the menu. Once Activity Monitor has loaded, expand the 'Processes' section. Scroll down to the SPID of the process you would like to kill. Right click on that line and select 'Kill Process'.
In SQL Server Management Studio Object Explorer, connect to the instance of the SQL Server Database Engine and then expand the instance. Expand Databases, and select the name of the user database you want to detach. Right-click the database name, point to Tasks, and then select Detach.
Simply not call KillAllProcesses
. RollbackTransactionsImmediately
is enough. It kills all sessions that are in that database right now.
KillAllProcesses
does not help you anyway because right after it is done killing sessions a new one could appear.
It happens to me all the time when I am trying to restore a database and there is an active connection somewhere and database will not restore until there are no more active connections to the database.
Usually what I do is, I execute the following set of commands to disconnect everyone and then restore the database .
ALTER DATABASE [DatabaseName]
SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
-- at this point all the users will be disconnected and the database is in
-- single-user mode
Use [DatabaseName] --<-- Grab that single connection
GO
Use [master] --<-- Disconnect from database and connect to Master DB for restore
GO
RESTORE DATABASE [DatabaseName] --<-- Finally restore database tara
FROM DISK .........
GO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With