DECLARE @killCommand NVARCHAR(1000);
DECLARE @sessionID INT;
-- 定义超时阈值(以分钟为单位)
DECLARE @idleTimeThreshold INT = 30;
-- 获取超过超时阈值的会话ID列表
SELECT
@sessionID = session_id
FROM
sys.dm_exec_sessions
WHERE
status = 'sleeping' -- 空闲状态
AND last_request_end_time <= DATEADD(minute, -@idleTimeThreshold, GETDATE());
WHILE @sessionID IS NOT NULL
BEGIN
SET @killCommand = N'KILL ' + CAST(@sessionID AS NVARCHAR(10));
-- 执行KILL命令
EXEC (@killCommand);
-- 获取下一个空闲会话ID
SELECT
@sessionID = session_id
FROM
sys.dm_exec_sessions
WHERE
status = 'sleeping'
AND session_id > @sessionID
AND last_request_end_time <= DATEADD(minute, -@idleTimeThreshold, GETDATE())
ORDER BY
session_id ASC;
END
标签:end,--,Server,会话,sessionID,Sql,DECLARE
From: https://www.cnblogs.com/Nine4Cool/p/18102079