Created
January 11, 2020 21:42
-
-
Save ronascentes/2fd1165ac8f5d4f0414fb5061a92f158 to your computer and use it in GitHub Desktop.
Kill all the current connections of a SQL instance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DECLARE @session_id INT, @sql NVARCHAR (4000); | |
DECLARE database_curs CURSOR FAST_FORWARD FOR | |
SELECT c.session_id | |
FROM sys.dm_exec_connections AS c | |
JOIN sys.dm_exec_sessions AS s ON c.session_id = s.session_id | |
WHERE c.session_id <> @@SPID AND s.is_user_process = 1; | |
OPEN database_curs; | |
FETCH NEXT FROM database_curs INTO @session_id; | |
WHILE (@@fetch_status <> -1) | |
BEGIN | |
IF (@@fetch_status <> -2) | |
BEGIN | |
SET @sql = N'KILL ' + CAST(@session_id AS nvarchar(6)); | |
EXEC sp_executesql @sql; | |
PRINT N'Session ID ' + CAST(@session_id AS nvarchar(6)) + N' was killed.'; | |
END; | |
FETCH NEXT FROM database_curs INTO @session_id; | |
END; | |
CLOSE database_curs; | |
DEALLOCATE database_curs; | |
GO |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment