Question

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

Was it helpful?

Solution

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.

OTHER TIPS

As far as I can tell, a real table can still be called [@sometable] the same as a table variable, but this is still a useful filter. The definitive XQuery filter seems to be that there is no @Database attribute on a node named Object.

with xmlnamespaces (default 'http://schemas.microsoft.com/sqlserver/2004/07/showplan')
select qp.query_plan
from sys.dm_exec_cached_plans p
cross apply sys.dm_exec_query_plan(p.plan_handle) qp
where qp.query_plan.exist('//Object[empty(@Database) and substring(@Table[1],1,2)="[@"]')
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top