My SQL Server 2005 doesn\'t restore a backup because of active connections. How can I force it?
When you right click on a database and click Tasks
and then click Detach Database
, it brings up a dialog with the active connections.
By clicking on the hyperlink under "Messages" you can kill the active connections.
You can then kill those connections without detaching the database.
More information here.
The interface has changed for SQL Server Management studio 2008, here are the steps (via: Tim Leung)
I prefer to do like this,
alter database set offline with rollback immediate
and then restore your database. after that,
alter database set online with rollback immediate
This code worked for me, it kills all existing connections of a database. All you have to do is change the line Set @dbname = 'databaseName' so it has your database name.
Use Master
Go
Declare @dbname sysname
Set @dbname = 'databaseName'
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
after this I was able to restore it
I ran across this problem while automating a restore proccess in SQL Server 2008. My (successfull) approach was a mix of two of the answers provided.
First, I run across all the connections of said database, and kill them.
DECLARE @SPID int = (SELECT TOP 1 SPID FROM sys.sysprocess WHERE dbid = db_id('dbName'))
While @spid Is Not Null
Begin
Execute ('Kill ' + @spid)
Select @spid = top 1 spid from master.dbo.sysprocesses
where dbid = db_id('dbName')
End
Then, I set the database to a single_user mode
ALTER DATABASE dbName SET SINGLE_USER
Then, I run the restore...
RESTORE DATABASE and whatnot
Kill the connections again
(same query as above)
And set the database back to multi_user.
ALTER DATABASE dbName SET MULTI_USER
This way, I ensure that there are no connections holding up the database before setting to single mode, since the former will freeze if there are.
Restarting SQL server will disconnect users. Easiest way I've found - good also if you want to take the server offline.
But for some very wierd reason the 'Take Offline' option doesn't do this reliably and can hang or confuse the management console. Restarting then taking offline works
Sometimes this is an option - if for instance you've stopped a webserver that is the source of the connections.
Try this:
DECLARE UserCursor CURSOR LOCAL FAST_FORWARD FOR
SELECT
spid
FROM
master.dbo.sysprocesses
WHERE DB_NAME(dbid) = 'dbname'--replace the dbname with your database
DECLARE @spid SMALLINT
DECLARE @SQLCommand VARCHAR(300)
OPEN UserCursor
FETCH NEXT FROM UserCursor INTO
@spid
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQLCommand = 'KILL ' + CAST(@spid AS VARCHAR)
EXECUTE(@SQLCommand)
FETCH NEXT FROM UserCursor INTO
@spid
END
CLOSE UserCursor
DEALLOCATE UserCursor
GO