I am currently trying to drop a database via the following code
using Microsoft.SqlServer.Management.Smo;
var server = new Server(Server);
server.KillAllProcesses("Db");
server.KillDatabase("Db");
Sometimes it works, but others I get the following exception:
Microsoft.SqlServer.Management.Smo.FailedOperationException: Kill database failed for Server 'Host1'.
---> Microsoft.SqlServer.Management.Common.ExecutionFailureException: An exception occurred while executing a Transact-SQL statement or batch.
---> System.Data.SqlClient.SqlException: Changes to the state or options of database 'Db' cannot be made at this time. The database is in single-user mode, and a user is currently connected to it.
Any ideas of how to reliably drop the database via code?
Using SQL Server Management StudioExpand Databases, right-click the database to delete, and then click Delete. Confirm the correct database is selected, and then click OK.
To delete a database, connect to an instance of the SQL Server, and then expand that instance. Expand Databases, select the database which need to be deleted. Right-click the database which need to be deleted, and then click Delete.
Dropping a database deletes the database from an instance of SQL Server and deletes the physical disk files used by the database. If the database or any one of its files is offline when it is dropped, the disk files are not deleted. These files can be deleted manually by using Windows Explorer.
To reliably delete the database via SMO it is sufficient to call server.KillDatabase("Db");
. MSDN does state that KillDatabase
drops active connections even if their examples are a bit misleading.
KillDatabase
issues ALTER DATABASE [Db] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
and then DROP DATABASE
. KillAllProcesses
list all connections and issues one kill per process as a separate batch; assuming KillAllProcesses
is asynchronous the exception is thrown when a kill happens after KillDatabase
sets the DB to the single-user mode.
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