Reputation: 1728
I am trying to delete sql server database. It gets deleted if it is not in use. If database is in use an exception occurred saying that can not delete database while it is in use
.
We can delete use database from management studio using option Close existing connection
.
But how can we do this using C# code?
Upvotes: 1
Views: 1869
Reputation:
ALTER DATABASE AdventureWorks2012
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE;
DROP DATABASE AdventureWorks2012;
Make a script file by writing above query in it.Then execute this script file as below :
string sqlConnectionString = "Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True";
FileInfo file = new FileInfo("C:\\myscript.sql");
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
Upvotes: 3