To find currently running SQL Queries/Processes:
In order to get all the command/queries currently in process, we used to run the following statement.
This will fetch us the list of System processes and User defined processes using which we can “Kill” the process with the SPID.
In the same way, there are situations where we need to know the detail about Query/Stored Proc which is currently running. For that we can make use of the query below,
FROM sys.dm_exec_requests req
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext
In the same way as we do in sp_who, we can kill the process with Session ID returned from the above.
Finding long running query stats:
To get statistics on the queries which has took more time to provide results/to get complete, we can use the query below. This will be helpful in case we plan to optimize database performance / latency reporting.
SELECT TOP 10
qs.total_elapsed_time / qs.execution_count / 1000000.0 AS average_seconds,
qs.total_elapsed_time / 1000000.0 AS total_seconds,
(CASE WHEN qs.statement_end_offset = -1
THEN LEN(CONVERT(NVARCHAR(MAX), qt.text)) * 2
ELSE qs.statement_end_offset END – qs.statement_start_offset)/2) AS individual_query,
o.name AS object_name,
DB_NAME(qt.dbid) AS database_name
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) as qt
LEFT OUTER JOIN sys.objects o ON qt.objectid = o.object_id
qt.dbid = DB_ID()