(if you are using .net it’s better to use ‘USING’ so the connection is properly disposed)
I wanted to find out what query was run on the connections that got opened and didn’t get closed. That way I could check where in code the sql was getting called and make sure the connection was getting closed there.
For this we are going to use the dynamic management view dm_exec_connections and dynamic management function dm_exec_sql_text.
The following query will give you list of connections on which the read or write was done 5 mins ago along with the last sql that was run on it.
SELECT *
FROM sys.dm_exec_connections C
CROSS APPLY sys.dm_exec_sql_text(C.most_recent_sql_handle) T
where
last_read < DATEADD(minute, -5, getdate()) or last_write < DATEADD(minute, -5, getdate())
here is a image of running the above query on my sql server
For this we are going to use the dynamic management view dm_exec_connections and dynamic management function dm_exec_sql_text.
- dm_exec_connections returns information about the established connections to this sql server instance. The column that we are most interested in is the most_recent_sql_handle, as this would have an handle to the sql that was run last before the connection was abandoned.
- dm_exec_sql_text is a table valued function which takes a sql_handle(or plan_handle) parameter and returns the database id and text(this is null if the if the object is encrypted) among other things.
The following query will give you list of connections on which the read or write was done 5 mins ago along with the last sql that was run on it.
SELECT *
FROM sys.dm_exec_connections C
CROSS APPLY sys.dm_exec_sql_text(C.most_recent_sql_handle) T
where
last_read < DATEADD(minute, -5, getdate()) or last_write < DATEADD(minute, -5, getdate())
here is a image of running the above query on my sql server