2

我的开发服务器上似乎有一个应用程序,它有很多打开的连接(它们应该在那里,但是一些错误的数据层被用来打开它们,忘记关闭它们)。我只是希望它们关闭,这样我就可以让其他应用程序在服务器上运行。如何强制关闭所有连接?

4

4 回答 4

6

使用以下脚本杀死来自特定主机/登录的非活动会话。您可以从计划的工作中使用它,当然您的首要任务应该是修复您的应用程序层。

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 + ']';
于 2008-12-15T12:13:06.870 回答
3

除了手动终止连接之外,您还可以

  • 处理连接。也就是说,以某种方式检索 Connection 对象并在它们上调用 .Close 和 .Dispose() 。使用“使用”将是理想的,因为它会自动为您调用 .Dispose()。
  • 回收您的应用程序池。
于 2008-12-15T11:13:18.830 回答
3

使用 sysprocesses 中的 last_batch 列来确定它是否真的处于活动状态。SPID > 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
于 2008-12-15T11:15:48.170 回答
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
于 2009-03-20T21:28:57.070 回答