martes, 26 de octubre de 2010

Killing connections that are opened for more than 24h in SQL Server

Killing connections that are opened for more than 24h in SQL Server

------------------- cut here -----------------------------------

DECLARE @PIDToKill VARCHAR(20)
DECLARE @exstring VARCHAR(20)

DECLARE KillCandidates CURSOR FOR
SELECT spid from master.dbo.sysprocesses p
join master.dbo.sysdatabases d on p.dbID = d.dbID
where d.name = 'XXX' and loginame = 'YYY'
and datediff(hh, login_time, getdate()) > 24
order by login_time;

OPEN KillCandidates;



FETCH NEXT FROM KillCandidates INTO @PIDToKill;
WHILE @@FETCH_STATUS = 0
BEGIN
set @exstring = 'KILL ' + @PIDToKill
EXEC sp_executesql @exstring

FETCH NEXT FROM KillCandidates INTO @PIDToKill;
END;
CLOSE KillCandidates;
DEALLOCATE KillCandidates;
GO