Friday, 11 May 2012

* Find out Long Running query using sp_who2 with DMV's

EXEC sp_who2
and see the result shown below. Find out rows with runnable status with highest CPUTime.
Sp_who2 will not display the text of the query, so we need to find out the text using dm_exec_requests and dm_exec_sql_text management views. The view dm_exec_requests will show the text of the query. All we need to do is to find out spid from the result of sp_who2 and filter it in dm_exec_requests using session_id column.

 The following code displays the text of the query.
 SELECT
        sql.text AS statement_text
FROM
        sys.dm_exec_requests  AS req
CROSS APPLY sys.dm_exec_sql_text(req.sql_handle) as sql
WHERE
    req.session_id=SPID