Labels

Thursday, 3 November 2016

Script to find currently running or active queries in SQL Server

Some times we used to get calls or mails from the user and asking for what are currently running queries in a particular instance and also will get complaints like queries are running slow.

For this scenario, we have to run the below query on a requested instance to find out currently running queries.


SELECT r.start_time [Start Time]
 ,session_ID [SPID]
 ,DB_NAME(database_id) [Database]
 ,SUBSTRING(t.TEXT, (r.statement_start_offset / 2) + 1, CASE 
   WHEN statement_end_offset = - 1
    OR statement_end_offset = 0
    THEN (DATALENGTH(t.TEXT) - r.statement_start_offset / 2) + 1
   ELSE (r.statement_end_offset - r.statement_start_offset) / 2 + 1
   END) [Executing SQL]
 ,STATUS
 ,command
 ,wait_type
 ,wait_time
 ,wait_resource
 ,last_wait_type
FROM sys.dm_exec_requests r
OUTER APPLY sys.dm_exec_sql_text(sql_handle) t
WHERE session_id != @@SPID
 AND session_id > 50 -- To avoid system queries
ORDER BY r.start_time

No comments:

Post a Comment