With the help of a user I've created a SQL Server Agent Job that stalks a few servers on my network every 10 minutes to collect all connections:
USE [msdb];
GO
DECLARE @ServerName varchar(50), @DynamicSQL NVARCHAR(MAX)
DECLARE @myTableVariable TABLE (id INT, ServerName varchar(50))
insert into @myTableVariable values(1,'TESLABSQL01T'),(2,'TESLABSQL02T')
-- select * from @myTableVariable -- use thisfor test
Declare VarCursor cursor for
Select ServerName from @myTableVariable
Open VarCursor
FETCH NEXT FROM VarCursor INTO @ServerName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @DynamicSQL='
INSERT INTO [msdb].[dbo].[ConnectionCounts_Remote]
SELECT ''' + @ServerName + ''' AS [ServerName]
,NAME AS DatabaseName
,COUNT(STATUS) AS [NumberOfConnections]
,GETDATE() AS [TimeStamp]
,hostname
,program_name
,loginame
FROM '+@ServerName+'.master.sys.databases sd
LEFT JOIN '+@ServerName+'.master.sys.sysprocesses sp ON sd.database_id = sp.dbid
WHERE database_id NOT BETWEEN 1 AND 4
GROUP BY NAME,hostname ,program_name ,loginame'
EXEC (@DynamicSQL)
FETCH NEXT FROM VarCursor INTO @ServerName
END
CLOSE VarCursor
DEALLOCATE VarCursor
So easy and so beautiful, the query connects every 10 minutes to TESLABSQL01T
and TESLABSQL02T
.
The problem is that on these remote servers if I execute sp_who2
I can still the users connected as DORMANT
.
So this means that my server is stalking those servers every 10 minutes but the connection is maintained.
How can I kill that connection not form the remote server but from the local server where the SQL Agent Job is executed?
Basically I'm trying to create a query that kill itself after is executed.
Any suggestion is welcome.