
A T-SQL script to kill multiple SQL Server sessions efficiently involves querying the sys.dm_exec_sessions view to identify active sessions based on criteria like user name or database name. This script demonstrates how to dynamically construct and execute KILL statements for those sessions, offering a practical solution for database administrators to manage server resources by terminating unnecessary or problematic sessions.
DECLARE @KillCmd NVARCHAR(MAX) = '';
SELECT @KillCmd = @KillCmd + 'KILL ' + CAST(session_id AS VARCHAR(5)) + '; '
FROM sys.dm_exec_sessions
WHERE database_id = DB_ID('YourDatabaseName') -- Replace YourDatabaseName with your target database
AND is_user_process = 1;
EXEC sp_executesql @KillCmd;
This script compiles a single command string that includes KILL statements for all sessions connected to a specified database, executing them in one go. Adjust the WHERE clause to target sessions based on your specific requirements, such as by user name or application name. Always test scripts in a safe environment before using them in production to avoid unintended disruptions.