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
| Parameter | Default | Effect 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 |
@ReqOlderThanMin | 0 (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] <> @@SPIDkeeps the script from killing its own session.KILLrefuses to end the session that issues it in any case.[is_user_process] = 1removes system sessions, which haveis_user_processset to0. System processes cannot be ended withKILLanyway.[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. Insys.dm_server_services, status4means Running, and the view covers the Database Engine, Full-Text, Launchpad and SQL Server Agent services. Reading this view needsVIEW SERVER STATEon SQL Server 2019 and earlier, andVIEW SERVER SECURITY STATEon 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 = 0the output is a list of the exactKILLstatements, which can be reviewed or compared withsys.dm_exec_sessionsbefore 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.
@OmitLoginkeeps 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.
@ReqOlderThanMinwith 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.
KILLends 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 atopen_transaction_countinsys.dm_exec_sessionsand atsys.dm_tran_active_transactions, which reportstransaction_begin_timeandtransaction_statefor each transaction on the instance. - Watch the rollback.
KILL <session_id> WITH STATUSONLYreports 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. UseWITH STATUSONLYto check progress. - The list is a snapshot. The
STATICcursor 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,
KILLrequires theALTER ANY CONNECTIONpermission, which is included with thesysadminandprocessadminfixed 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 IMMEDIATErolls 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. SetAUTO_UPDATE_STATISTICS_ASYNCtoOFFfirst, because the background statistics thread takes a connection to the database.
Practical Tips
- Preview with the cursor query. Copy the
SELECTfrom 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 onSales.@ForLoginwith an empty@ForDatabaseends that login's sessions in every database. - Use the N prefix for logins. The login variables are
NVARCHAR(128), matchinglogin_name, soN'DOMAIN\user'avoids implicit conversions and handles non-ASCII names. - Restore sequence. Set
@ForDatabaseto the target database and@Confirm = 1, run the script, and start the restore immediately. For a restore, theSINGLE_USER WITH ROLLBACK IMMEDIATEstatement described above is the alternative. - Schedule only the narrow cases. A SQL Agent job with
@SPIDState = 'S',@HasOpenTran = 'Y'and a large@ReqOlderThanMinis 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.KILLis commonly used to end a process that is blocking other important processes with locks. - Do not kill service sessions by hand.
KILLcannot 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
- VladDBA/SQL-Server-Scripts on GitHub — repository containing the KillSPIDs.sql script this one is based on
- sys.dm_exec_sessions (Transact-SQL) — session columns, status values, database_id and open_transaction_count
- KILL (Transact-SQL) — syntax, WITH STATUSONLY, restrictions and permissions
- sys.dm_server_services (Transact-SQL) — service_account and status values for the Database Engine and related services
- sys.dm_tran_active_transactions (Transact-SQL) — transaction start time and state for open transactions
- DECLARE CURSOR (Transact-SQL) — LOCAL, STATIC and FORWARD_ONLY cursor options
- ALTER DATABASE SET options (Transact-SQL) — SINGLE_USER and the WITH ROLLBACK IMMEDIATE termination clause
Posts in this series
- SQL Server Scripts and Commands: DBA Reference All Versions
- SQL Server DBCC CHECKIDENT: Bulk Identity Column Analysis
- SQL Server Error Log Search Script: xp_readerrorlog
- SQL Server Search Stored Procedure and View Text
- SQL Server Agent Job Failure History Report
- SQL Server Kill Sessions: Filtered SPID Management
- SQL Server MAXDOP Recommendation Script
- SQL Server Max Server Memory Calculator Script
- SQL Server Object Dependencies Report: Find All References
- SQL Server DBCC CHECKIDENT: Check and Reseed Identity
- List All Tables Across All Databases in SQL Server
- Configure Database Mail and Send a Test Message
- Audit Server Configuration Drift with sys.configurations
- Check AG Replica Health with sys.dm_hadr_availability_replica_states
- Audit Per-Database MAXDOP, CE and Sniffing Config Overrides