Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK)

后端 未结 14 1578
-上瘾入骨i
-上瘾入骨i 2020-11-28 17:28

I have a development database that re-deploy frequently from a Visual Studio Database project (via a TFS Auto Build).

Sometimes when I run my build I get this error:

14条回答
  •  一个人的身影
    2020-11-28 17:46

    The accepted answer has the drawback that it doesn't take into consideration that a database can be locked by a connection that is executing a query that involves tables in a database other than the one connected to.

    This can be the case if the server instance has more than one database and the query directly or indirectly (for example through synonyms) use tables in more than one database etc.

    I therefore find that it sometimes is better to use syslockinfo to find the connections to kill.

    My suggestion would therefore be to use the below variation of the accepted answer from AlexK:

    USE [master];
    
    DECLARE @kill varchar(8000) = '';  
    SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), req_spid) + ';'  
    FROM master.dbo.syslockinfo
    WHERE rsc_type = 2
    AND rsc_dbid  = db_id('MyDB')
    
    EXEC(@kill);
    

提交回复
热议问题