我的开发服务器上似乎有一个应用程序,它有很多打开的连接(它们应该在那里,但是一些坏的数据层被用来打开它们,忘了关闭它们)。我只是希望它们关闭,以便我可以在服务器上运行其他应用程序。如何强制关闭所有连接?
答案 0 :(得分:5)
使用以下脚本从特定主机/登录名中终止非活动会话。您可以从预定的工作中使用它,当然您的首要任务是修复您的应用层。
SET NOCOUNT ON;
DECLARE @host VARCHAR(50), @login NVARCHAR(128);
SET @host = 'fooHost'; --NULL to kill sessions from all hosts.
SET @login = 'fooLogin';
DECLARE @cmd NVARCHAR(255);
DECLARE @possition INT, @total INT, @selSpid SMALLINT;
DECLARE @spidInfo TABLE
(
[id] INT IDENTITY(1,1),
spid SMALLINT,
loginame NVARCHAR(128)
);
INSERT @spidInfo(spid, loginame)
SELECT session_id, login_name
FROM sys.dm_exec_sessions
WHERE is_user_process = 1 AND [status] = 'sleeping' AND
login_name = @login AND [host_name] = COALESCE(@host, [host_name]);
SELECT @total = @@IDENTITY, @selSpid = 0, @possition = 0;
WHILE @possition < @total
BEGIN
SELECT TOP 1 @selSpid = spid, @possition = [id]
FROM @spidInfo
WHERE [ID] > @possition
SET @cmd = N'KILL ' + CAST(@selSpid AS NVARCHAR(10));
EXEC sp_executesql @cmd;
PRINT 'SessionId = ' + CAST(@selSpid AS NVARCHAR(10)) + '[' + @login +
'] killed by ' + system_user + ' at ' + CAST(GETDATE() AS VARCHAR(50));
END;
IF (@total = 0)
PRINT 'No sessions owned by user ' + '[' + @login + ']';
答案 1 :(得分:3)
除了手动终止连接外,您还可以
答案 2 :(得分:3)
使用sysprocesses中的last_batch列来计算它是否真正有效。 SPID&gt; 50(或者是> = 50?)以避免杀死系统SPID。
将此与您想要的睡眠时间和KILL spid进行比较。
你必须循环。
DECLARE @kill_id smallint
DECLARE spid_cursor CURSOR FOR
select spid from sysprocesses
where dbid = > 4 and last_batch < dateadd(hour, -24, getdate()) and spid >= 50
OPEN spid_cursor
FETCH NEXT FROM spid_cursor INTO @kill_id
WHILE (@@FETCH_STATUS = 0)
BEGIN
-- Kill the current spid here
-- KILL @kill_id <---This line will not work
-- Get the next cursor row
FETCH NEXT FROM spid_cursor INTO @kill_id
END
CLOSE spid_cursor
DEALLOCATE spid_cursor
答案 3 :(得分:2)
首先运行此命令以查找有问题的数据库.....
SELECT DB_NAME(dbid) as 'Database Name',
COUNT(dbid) as 'Total Connections'
FROM master.dbo.sysprocesses WITH (nolock)
WHERE dbid > 0
GROUP BY dbid
SELECT @@MAX_CONNECTIONS AS 'Max Allowed Connections'
然后运行此命令以终止与所需数据库的连接
USE master
go
DECLARE @dbname sysname
SET @dbname = 'Events'
DECLARE @spid int
SELECT @spid = min(spid) from master.dbo.sysprocesses where dbid = db_id(@dbname)
WHILE @spid IS NOT NULL
BEGIN
EXECUTE ('KILL ' + @spid)
SELECT @spid = min(spid) from master.dbo.sysprocesses where dbid = db_id(@dbname) AND spid > @spid
END