A T-SQL script for killing multiple SQL Server sessions

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.

Related Posts

Troubleshooting Missing SQL Server Statistics

Learn how to diagnose and fix missing SQL Server statistics through a practical troubleshooting guide, including step-by-step solutions and best practices.

Read more

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from The DBA Hub

Subscribe now to keep reading and get access to the full archive.

Continue reading