Function to Join CahcedPlan, Query Plan and Sql_text

The cache plan handle can be found by querying select * from sys.dm_exec_cached_plans How do I get the sql text and Query Plan for this plan handle? create function returnSQL(@planhandle varbinary(max)) returns table As return select sql.text,pc.usecounts,pc.cacheobjtype,pc.objtype,pc.size_in_bytes, Pq.query_plan From Sys.dm_exec_sql_text(@planhandle) as sql cross join Sys.dm_exec_query_plan(@planhandle) as pq join Sys.dm_exec_cached_plans as pc on pc.plan_handle = @planhandle; […]