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

后端 未结 14 1504
-上瘾入骨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 18:03

    Little known: the GO sql statement can take an integer for the number of times to repeat previous command.

    So if you:

    ALTER DATABASE [DATABASENAME] SET SINGLE_USER
    GO
    

    Then:

    USE [DATABASENAME]
    GO 2000
    

    This will repeat the USE command 2000 times, force deadlock on all other connections, and take ownership of the single connection. (Giving your query window sole access to do as you wish.)

    0 讨论(0)
  • 2020-11-28 18:03

    Matthew's supremely efficient script updated to use the dm_exec_sessions DMV, replacing the deprecated sysprocesses system table:

    USE [master];
    GO
    
    DECLARE @Kill VARCHAR(8000) = '';
    
    SELECT
        @Kill = @Kill + 'kill ' + CONVERT(VARCHAR(5), session_id) + ';'
    FROM
        sys.dm_exec_sessions
    WHERE
        database_id = DB_ID('<YourDB>');
    
    EXEC sys.sp_executesql @Kill;
    

    Alternative using WHILE loop (if you want to process any other operations per execution):

    USE [master];
    GO
    
    DECLARE @DatabaseID SMALLINT = DB_ID(N'<YourDB>');    
    DECLARE @SQL NVARCHAR(10);
    
    WHILE EXISTS ( SELECT
                    1
                   FROM
                    sys.dm_exec_sessions
                   WHERE
                    database_id = @DatabaseID )    
        BEGIN;
            SET @SQL = (
                        SELECT TOP 1
                            N'kill ' + CAST(session_id AS NVARCHAR(5)) + ';'
                        FROM
                            sys.dm_exec_sessions
                        WHERE
                            database_id = @DatabaseID
                       );
            EXEC sys.sp_executesql @SQL;
        END;
    
    0 讨论(0)
提交回复
热议问题