Click here to Skip to main content
15,915,094 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I know the following code can be used to detach a Sql server database:
C#
SqlCommand com = new SqlCommand("USE master; exec sp_detach_db mydatabase", con);
com.ExecuteNonQuery();

But it doesn't always work, just for some cases the database is currently in use without knowing why and what process is using it. If using Sql Server manager, I can refresh all the databases and can execute the detach stored proc successfully. But I want to detach the database (whenever I want) using code, could you please give me any solution?

I discovered that my database was really in use, because I had used sql connection to read data from it, however I tried diposing all sql stuffs (sql connection, sql dataadapter...) before detaching but it still throws the exception. Could you have any ideas on how to make the database not currently be in use any more?
Your helps would be highly appreciated!
Thank you very much!
Posted
Updated 4-Nov-11 13:40pm
v2

 
Share this answer
 
Thank you for the good link.
I have read it before posting my question here. Moreover, that's a guide through how to detach, attach database using code when the database is not currently in use. My situation is another problem, We have to make the database not be in use first.

I found some solutions here, however sometimes they works very slowly:
SQL
ALTER DATABASE mydatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE
or
ALTER DATABASE mydatabase SET OFFLINE WITH ROLLBACK IMMEDIATE
or
Declare @DBname sysname
Set @DBname = 'mydatabase'
Declare @spid int
SELECT @spid = MIN(spid) FROM master.dbo.sysprocesses WHERE dbid = db_id(@DBname)
WHILE @spid is not null
BEGIN
EXECUTE('Kill ' + @spid)
SELECT @spid = MIN(spid) FROM master.dbo.sysprocesses WHERE dbid = db_id(@DBname) AND spid > @spid
END


USE MASTER before one of snippets above and then use the detach command.
If there are some connections to the database, they work really slow!
Thank you!
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900