Tuesday, October 22, 2024

SQL Script to Terminate All Active Connections to a Specific Database || Kill Database connections

 -- Declare a cursor to iterate through the sessions

DECLARE @sessionId INT;

DECLARE kill_cursor CURSOR FOR

    SELECT session_id

    FROM sys.dm_exec_sessions

    WHERE database_id = DB_ID('DBName');


-- Open the cursor and loop through the sessions

OPEN kill_cursor;


FETCH NEXT FROM kill_cursor INTO @sessionId;


WHILE @@FETCH_STATUS = 0

BEGIN

    -- Print the session ID to be killed (for verification purposes)

    PRINT 'Killing session: ' + CAST(@sessionId AS VARCHAR(10));


    -- Kill the session

    EXEC('KILL ' + @sessionId);


    FETCH NEXT FROM kill_cursor INTO @sessionId;

END


-- Close and deallocate the cursor

CLOSE kill_cursor;

DEALLOCATE kill_cursor;