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?
-
Could this be useful to you : stackoverflow.com/questions/1145892/… ?Andy M– Andy M2012-11-05 07:16:18 +00:00Commented Nov 5, 2012 at 7:16
Add a comment
|
2 Answers
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);
2 Comments
Pranav
why you need to create seperate .SQL for this,you can just Execute it through writing query in string itself..:):P
Kashif Hanif
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.
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:-
1 Comment
Kashif Hanif
"Fire this Query through your code and go ahead:" yes Pranav it work for me......i am too happy.thanks for help