0

Is there a way to determine the plan handle for the query plan of an executing query by that query's text?

Perhaps in any of the DMVs?

(I'm trying to find the query stats on an ad-hoc query.)

2
  • 1
    Check this link
    – Jacob H
    Commented Nov 13, 2019 at 20:37
  • 1
    Try to get QueryHash from an estimated plan and then use the query hash to find the query in sys.dm_exec_query_stats Commented Nov 14, 2019 at 7:10

1 Answer 1

2

Derived from https://stackoverflow.com/questions/7359702/how-do-i-obtain-a-query-execution-plan

DECLARE @SearchForSql AS NVARCHAR(MAX) = 'SQL TEXT'

SELECT UseCounts, Cacheobjtype, Objtype, TEXT, query_plan
FROM sys.dm_exec_cached_plans 
CROSS APPLY sys.dm_exec_sql_text(plan_handle)
CROSS APPLY sys.dm_exec_query_plan(plan_handle)
WHERE Text LIKE CONCAT('%' ,@SearchForSql,'%')
    AND Text NOT LIKE '%-- Self Reference Marker --%'

Note: The "NOT LIKE" is there to ensure that you don't find the statement you are running, which is inherently self referencing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.