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

后端 未结 14 1510
-上瘾入骨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:44

    @AlexK wrote a great answer. I just want to add my two cents. The code below is entirely based on @AlexK's answer, the difference is that you can specify the user and a time since the last batch was executed (note that the code uses sys.dm_exec_sessions instead of master..sysprocess):

    DECLARE @kill varchar(8000);
    set @kill =''
    select @kill = @kill + 'kill ' +  CONVERT(varchar(5), session_id) + ';' from sys.dm_exec_sessions 
    where login_name = 'usrDBTest'
    and datediff(hh,login_time,getdate()) > 1
    --and session_id in (311,266)    
    exec(@kill)
    

    In this example only the process of the user usrDBTest which the last batch was executed more than 1 hour ago will be killed.

提交回复
热议问题