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:
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!