1

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?

1

2 Answers 2

3
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);
Sign up to request clarification or add additional context in comments.

2 Comments

why you need to create seperate .SQL for this,you can just Execute it through writing query in string itself..:):P
Mr Wajid Ali thanks for Ur help.it has solved my 2 days problem.it work fine for me.thanks again.......i was only trying to set db offline but it was not working......"With role back immediate" it has worked for me as suggested by you.thanks again.
2

The easy way on a MS SQL Server to kick all users off is:

ALTER DATABASE [MyDB] SET Single_User WITH Rollback Immediate
GO

Fire this Query through your code and go ahead:-

SOURCE:-

1 Comment

"Fire this Query through your code and go ahead:" yes Pranav it work for me......i am too happy.thanks for help

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.