SQL Server Kill Sessions: Filtered SPID Management

This T-SQL script kills one or more SQL Server sessions (SPIDs) chosen by filters: login, database, session state, open transactions and the age of the last request. It reads sys.dm_exec_sessions, builds a KILL statement for each match, and by default only prints what it would do.

Purpose and Overview

Clearing connections off a database before a restore, a detach or a maintenance window is a routine job, and KILL handles it one session at a time. Doing it for thirty sessions means looking up thirty session IDs, typing thirty statements and hoping none of them belongs to a service account or to the session you are working in. A loop with filters turns that into one reviewed run.

The script excludes its own session and every session that is not a user process, and it skips sessions that are logged in with the account of a running SQL Server service. It has six filters and one safety switch, @Confirm. With @Confirm = 0 it lists the KILL statements it would run and executes none of them. With @Confirm = 1 it runs them.

Common jobs it covers:

  • Clearing all connections to one database before a restore or detach.
  • Killing every session for one application login.
  • Removing only sleeping sessions while running queries continue.
  • Ending sessions that hold open transactions and are blocking other work.
  • Disconnecting sessions whose last request started more than a set number of minutes ago.

Code Breakdown

The script runs in master. Set the filters at the top, run it once with @Confirm = 0 to read the list, then set @Confirm = 1 and run it again.

 1USE [master];
 2GO
 3
 4DECLARE  @SPID            SMALLINT
 5        ,@ExecSQL         VARCHAR(11)
 6        ,@Confirm         BIT
 7        ,@ForLogin        NVARCHAR(128)
 8        ,@OmitLogin       NVARCHAR(128)
 9        ,@SPIDState       VARCHAR(1)
10        ,@ForDatabase     NVARCHAR(128)
11        ,@HasOpenTran     VARCHAR(1)
12        ,@ReqOlderThanMin INT;
13
14SET @Confirm         = 0;    /* 0 = list only, 1 = execute the KILL statements */
15SET @ForLogin        = N'';  /* only this login; empty = all logins */
16SET @OmitLogin       = N'';  /* every login except this one; empty = omit none */
17SET @SPIDState       = '';   /* S = sleeping, R = running; empty = any state */
18SET @ForDatabase     = N'';  /* only sessions whose current database is this one; empty = all */
19SET @HasOpenTran     = '';   /* Y = open transactions only, N = none open; empty = either */
20SET @ReqOlderThanMin = 0;    /* last request started at least N minutes ago; 0 = any */
21
22DECLARE KillSPIDCursor CURSOR LOCAL STATIC READ_ONLY FORWARD_ONLY FOR
23  SELECT [session_id]
24  FROM   [sys].[dm_exec_sessions]
25  WHERE  [session_id] <> @@SPID
26    AND  [is_user_process] = 1
27    AND  (@ForLogin = N''    OR [login_name] = @ForLogin)
28    AND  (@OmitLogin = N''   OR [login_name] <> @OmitLogin)
29    AND  (@ForDatabase = N'' OR [database_id] = DB_ID(@ForDatabase))
30    AND  [login_name] NOT IN (SELECT [service_account]
31                              FROM   [sys].[dm_server_services]
32                              WHERE  [status] = 4)
33    AND  (   @SPIDState = ''
34          OR (@SPIDState = 'S' AND [status] = N'Sleeping')
35          OR (@SPIDState = 'R' AND [status] = N'Running'))
36    AND  (   @ReqOlderThanMin = 0
37          OR [last_request_start_time] <= DATEADD(MINUTE, -@ReqOlderThanMin, GETDATE()))
38    AND  (   @HasOpenTran = ''
39          OR (@HasOpenTran = 'Y' AND [open_transaction_count] > 0)
40          OR (@HasOpenTran = 'N' AND [open_transaction_count] = 0));
41
42OPEN KillSPIDCursor;
43FETCH NEXT FROM KillSPIDCursor INTO @SPID;
44
45WHILE @@FETCH_STATUS = 0
46BEGIN
47    SET @ExecSQL = 'KILL ' + CAST(@SPID AS VARCHAR(5)) + ';';
48    IF @Confirm = 1
49        EXEC (@ExecSQL);
50    ELSE
51        PRINT 'Would run: ' + @ExecSQL;
52    FETCH NEXT FROM KillSPIDCursor INTO @SPID;
53END;
54
55CLOSE KillSPIDCursor;
56DEALLOCATE KillSPIDCursor;

Variable Declarations

Two working variables, @SPID and @ExecSQL, carry the session ID and the statement text. @ExecSQL is VARCHAR(11), exactly long enough for KILL 32767;. The remaining variables are the safety switch and the six filters. All of them default to empty or zero, which means "do not filter on this".

Safety Switch: @Confirm

@Confirm is a BIT that defaults to 0. In that state the loop prints one Would run: KILL n; line per matching session and executes nothing, so the list of targets is visible before anything is ended. Set it to 1 only after reading that list.

Filter Parameters

ParameterDefaultEffect when set
@ForLogin'' (all)Only sessions for this login name
@OmitLogin'' (none)Every session except this login
@SPIDState'' (any)S = Sleeping only, R = Running only
@ForDatabase'' (all)Only sessions whose current database is this one
@HasOpenTran'' (either)Y = open transactions only, N = no open transactions
@ReqOlderThanMin0 (any)Only sessions whose last request started at least N minutes ago

The filters combine with AND. Each one is written as (@Filter = empty OR column = @Filter), so an unset filter drops out of the predicate. @ForLogin and @OmitLogin can be used together, though that is rarely useful.

Session Selection

The cursor reads sys.dm_exec_sessions, which returns one row per authenticated session and covers user connections and internal tasks. Three conditions are always applied:

  • [session_id] <> @@SPID keeps the script from killing its own session. KILL refuses to end the session that issues it in any case.
  • [is_user_process] = 1 removes system sessions, which have is_user_process set to 0. System processes cannot be ended with KILL anyway.
  • [login_name] NOT IN (SELECT [service_account] FROM [sys].[dm_server_services] WHERE [status] = 4) removes sessions logged in as the account of a running service. In sys.dm_server_services, status 4 means Running, and the view covers the Database Engine, Full-Text, Launchpad and SQL Server Agent services. Reading this view needs VIEW SERVER STATE on SQL Server 2019 and earlier, and VIEW SERVER SECURITY STATE on SQL Server 2022 and later.

The @SPIDState filter compares against the session status, which is Running, Sleeping, Dormant or Preconnect. A dormant session was reset by connection pooling and is waiting in a prelogin state, so the S filter does not select it.

The @ForDatabase filter compares against the session's database_id, which is the ID of the current database for each session.

last_request_start_time is the time the last request began, and that time includes the request that is executing now. The @ReqOlderThanMin filter is therefore about how long ago the latest request started, not about how long the session has been idle. A query that started three hours ago and is still running matches a 120-minute threshold. Combine it with @SPIDState = 'S' to target sessions that are sleeping and have been for a while.

Cursor Definition

LOCAL limits the cursor to the batch. STATIC means the cursor shows the result set as it was when it was opened and keeps a temporary copy in tempdb, so sessions that connect or disconnect while the loop runs do not change the list. FORWARD_ONLY is allowed together with STATIC in Transact-SQL cursors, and READ_ONLY states that the script only reads rows.

Loop and KILL Execution

For each row the script builds the statement as a string, 'KILL ' + CAST(@SPID AS VARCHAR(5)) + ';', and either prints it or runs it with EXEC(). @@FETCH_STATUS = 0 keeps the loop going until the cursor runs out of rows. CLOSE and DEALLOCATE then release the cursor.

Key Benefits and Use Cases

  • Dry run by default. With @Confirm = 0 the output is a list of the exact KILL statements, which can be reviewed or compared with sys.dm_exec_sessions before anything is ended.
  • One database at a time. Set @ForDatabase = N'YourDB' to clear one database and leave the rest of the instance alone.
  • Protect one login. @OmitLogin keeps an application service login or your own login connected while everything else is cleared.
  • Remove sleeping sessions. @SPIDState = 'S' ends sessions that are running no requests and leaves active queries running.
  • Find forgotten transactions. @HasOpenTran = 'Y' with @SPIDState = 'S' selects sleeping sessions that still hold an open transaction, often left by client code that never committed or by implicit transaction mode.
  • Stale connection cleanup. @ReqOlderThanMin with the sleeping filter removes connections whose last activity is old.
  • Service protection. Sessions that belong to running SQL Server service accounts are skipped automatically.

Performance Considerations

  • Rollback can be slow. KILL ends the session and stops its transactions, and when the session has a lot of work to undo, the statement can take some time to complete. This is most noticeable when a long transaction is rolled back. Before ending a session with an open transaction, look at open_transaction_count in sys.dm_exec_sessions and at sys.dm_tran_active_transactions, which reports transaction_begin_time and transaction_state for each transaction on the instance.
  • Watch the rollback. KILL <session_id> WITH STATUSONLY reports the percentage of rollback completed and the estimated time left, and does not end or roll back anything itself. It fails with error 6120 if no rollback is in progress for that session.
  • Do not repeat a plain KILL. A session ID is released when its connection ends and can be assigned to a new connection. Repeating KILL <session_id> after the rollback finishes can therefore end an unrelated new session. Use WITH STATUSONLY to check progress.
  • The list is a snapshot. The STATIC cursor fixes the session list when it opens. If a session ends and its ID is reused before the loop reaches it, the script kills the new session. On a busy instance, keep the gap between the dry run and the real run short and use the dry run only as a guide.
  • Permission. On SQL Server, KILL requires the ALTER ANY CONNECTION permission, which is included with the sysadmin and processadmin fixed server roles.
  • Cursor cost. For dozens or a few hundred sessions the cursor is not a factor.
  • Single-user alternative. To disconnect everyone from one database, ALTER DATABASE [YourDB] SET SINGLE_USER WITH ROLLBACK IMMEDIATE rolls back incomplete transactions and disconnects all other connections to the database in one statement. Be aware that the database stays in single-user mode until you set it back, even if the session that set it signs out, and then one other user can connect. Set AUTO_UPDATE_STATISTICS_ASYNC to OFF first, because the background statistics thread takes a connection to the database.

Practical Tips

  • Preview with the cursor query. Copy the SELECT from the cursor definition, set the variables, and run it with the session columns you care about (login_name, host_name, program_name, status, open_transaction_count). That shows who is about to lose a connection, not just a number.
  • Combine filters deliberately. @ForDatabase = N'Sales' with @SPIDState = 'S' ends only sleeping sessions on Sales. @ForLogin with an empty @ForDatabase ends that login's sessions in every database.
  • Use the N prefix for logins. The login variables are NVARCHAR(128), matching login_name, so N'DOMAIN\user' avoids implicit conversions and handles non-ASCII names.
  • Restore sequence. Set @ForDatabase to the target database and @Confirm = 1, run the script, and start the restore immediately. For a restore, the SINGLE_USER WITH ROLLBACK IMMEDIATE statement described above is the alternative.
  • Schedule only the narrow cases. A SQL Agent job with @SPIDState = 'S', @HasOpenTran = 'Y' and a large @ReqOlderThanMin is a defensible way to remove abandoned sessions. A job that kills everything on a schedule is not.
  • Check blocking first. If the goal is to relieve a blocking chain, find the head blocker in sys.dm_exec_requests (blocking_session_id) and end only that session. KILL is commonly used to end a process that is blocking other important processes with locks.
  • Do not kill service sessions by hand. KILL cannot end system processes or processes running an extended stored procedure, and sessions such as the checkpoint, lazy writer and lock monitor tasks should be left alone.

Conclusion

This script ends sessions by login, database, state, open transactions and request age, skips its own session, system sessions and service accounts, and prints the KILL statements by default so the list can be read before anything runs. Use it for restores, maintenance windows and clearing abandoned connections, and reach for SINGLE_USER WITH ROLLBACK IMMEDIATE when the goal is simply to empty one database.

References

Posts in this series