Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reliably drop a database on SQL Server 2008 via C#

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?

like image 634
Konstantinos Avatar asked Oct 31 '12 18:10

Konstantinos


People also ask

How do I delete a database in SQL server 2008 r2?

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.

How to delete db in SQL server?

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.

What is database drop?

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.


1 Answers

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.

like image 136
Serge Belov Avatar answered Nov 06 '22 19:11

Serge Belov