Queries Taking Longer Than One Hour of CPU
A query that finds all queries whose cumulative CPU worker time exceeds one hour, with plan handles for eviction.
Which queries have burned more than an hour of CPU in total since the plan cache was last cleared? This query reports each one's execution count, cumulative worker time in hours, average seconds per execution, row counts, the statement text, database and plan handle - so you can decide whether to tune it or evict its plan (the commented DBCC FREEPROCCACHE at the bottom shows how).
SELECT
qs.execution_count as [Execution Count],
(total_worker_time / 1000000) / 60 / 60 as [Worker Time (H)],
Cast((total_worker_time / 1000000.0) / qs.execution_count as Decimal(16, 2)) as [Seconds / Execute],
qs.total_rows as [Total Rows], qs.last_rows as [Last Rows], qs.min_rows as [Min Rows], qs.max_rows as [Max Rows],
SUBSTRING(qt.text,qs.statement_start_offset/2 +1,
(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 [Query Text],
qt.dbid as DatabaseId,
DB_NAME (qt.dbid) as [Datebase], qt.objectid as ObjectId,
plan_handle as [Plan Handle]
FROM
sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
WHERE
--qt.text like '%SELECT%'
(qs.total_worker_time / 1000000) / 60 / 60 >= 1
ORDER BY
qs.execution_count DESC
--dbcc freeproccache(0x050007009FD80D644001C92F0A0000000000000000000000)