SQL Server 2014 – How to Query Plan Cache for All Queries Using Table Variable

plan-cachesql serversql server 2014

Is there a way to query the sql plan cache for all query's using a table variable?

Best Answer

One way to do it is you could use the system DMVs to do a wildcard contains search on the cached query plans' text like so:

SELECT databases.[name] AS DatabaseName, Plans.objtype AS ObjectType, PlanText.text AS PlanText
FROM sys.dm_exec_cached_plans AS Plans -- Cached Query Plans
CROSS APPLY sys.dm_exec_sql_text(Plans.plan_handle) AS PlanText -- Query Plan Text
INNER JOIN sys.types -- Data Types (inclusive of User Defined)
    ON PlanText.[text] LIKE '%' + types.[name] + '%'
INNER JOIN master.sys.databases -- Databases
    ON PlanText.[dbid] = databases.database_id
WHERE types.is_user_defined = 1
    AND types.is_table_type = 1 -- Filter on only the User Defined Table Types

This will return the database of the cached query plan, the object type (View, Procedure, Ad-Hoc etc), and the query plan's text itself. One potential downside to this is if you have a user-defined table type that has a very common name used for other things in other queries, and therefor you might get extra results back due to false positives on the contains search.