Skip to content

Instantly share code, notes, and snippets.

@mbourgon
Last active December 16, 2015 08:39
Show Gist options
  • Save mbourgon/5407368 to your computer and use it in GitHub Desktop.
Save mbourgon/5407368 to your computer and use it in GitHub Desktop.
Extended Events - list servers connecting to your SQL Server.
-- If the Event Session Exists, drop it first
IF EXISTS (SELECT 1
FROM sys.server_event_sessions
WHERE name = 'UnknownAppHosts')
DROP EVENT SESSION UnknownAppHosts
ON SERVER;
-- Create the Event Session
CREATE EVENT SESSION UnknownAppHosts
ON SERVER
ADD EVENT sqlserver.login(
ACTION(sqlserver.client_hostname)
--add filters on the login here. This would only watch anonymous .Net apps
-- WHERE ([sqlserver].[client_app_name] LIKE '.Net SQLClient Data Provider%')
WHERE ([sqlserver].client_hostname NOT LIKE '%-MQ-%')
)
ADD TARGET package0.histogram
( SET slots = 50, -- Adjust based on expected number of "buckets" needed
filtering_event_name='sqlserver.login',
source_type=1,
source='sqlserver.client_hostname'
)
WITH(MAX_DISPATCH_LATENCY =1SECONDS);
GO
-- Start the Event Session
ALTER EVENT SESSION UnknownAppHosts
ON SERVER
STATE = start ;
GO
-- Parse the session data to determine the host/database.
-- When you stop the session, the records go AWAY, so make sure to run this before that!
SELECT slot.value('./@count', 'int') AS [Count] ,
slot.query('./value').value('.', 'varchar(20)')
FROM
(
SELECT CAST(target_data AS XML) AS target_data
FROM sys.dm_xe_session_targets AS t
INNER JOIN sys.dm_xe_sessions AS s
ON t.event_session_address = s.address
WHERE s.name = 'UnknownAppHosts'
AND t.target_name = 'Histogram') AS tgt(target_data)
CROSS APPLY target_data.nodes('/HistogramTarget/Slot') AS bucket(slot)
ORDER BY slot.value('./@count', 'int') DESC
GO
----------------------------------
--WHEN AND ONLY WHEN YOU'RE DONE--
----------------------------------
-- Stop the Event Session
ALTER EVENT SESSION UnknownAppHosts
ON SERVER
STATE = STOP ;
GO
-- Drop the Event Session
DROP EVENT SESSION UnknownAppHosts
ON SERVER;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment