When restoring a backup, how do I disconnect all active connections?

后端 未结 10 1067
失恋的感觉
失恋的感觉 2020-12-22 15:26

My SQL Server 2005 doesn\'t restore a backup because of active connections. How can I force it?

10条回答
  •  清酒与你
    2020-12-22 16:03

    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.

提交回复
热议问题