sql-serverxmlt-sqlxml-parsingsql-execution-plan

Used statistics from XML plan cache for query with given QueryPlanHash


I'm using SQL Server 2016/2019. I want to extract (for given @QueryPlanHash BINARY(8) = 0x397CEDB37FA0E1D2) from execution plan XML in cache - which statistics was used to generate that plan.

This section in XML plan looks like that:

<OptimizerStatsUsage>
    <StatisticsInfo Database="[MyDatabaseName]" Schema="[dbo]" Table="[MyTable_1]" 
        Statistics="[IX_MyTable_1_Field1]" ModificationCount="2" 
        SamplingPercent="100" LastUpdate="2024-06-13T13:39:04.41" />
    <StatisticsInfo Database="[MyDatabaseName]" Schema="[dbo]" Table="[MyTable_2]" 
        Statistics="[_WA_Sys_00000015_4B4D17CD]" ModificationCount="0" 
        SamplingPercent="100" LastUpdate="2024-06-13T12:06:33.17" />
</OptimizerStatsUsage> 

If it is possible I want information:

  1. Schema
  2. Table
  3. Statistics
  4. ModificationCount
  5. SamplingPercent
  6. LastUpdate

Solution

  • You can use SQL-XQuery for this. .nodes will shred the XML into separate rows, and .value pulls out a single value.

    WITH XMLNAMESPACES (
        DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan'
    )
    SELECT
      [Schema]          = x1.statsinfo.value('@Schema', 'sysname'),
      [Table]           = x1.statsinfo.value('@Table', 'sysname'),
      [Statistics]      = x1.statsinfo.value('@Statistics', 'sysname'),
      ModificationCount = x1.statsinfo.value('@ModificationCount', 'bigint'),
      SamplingPercent   = x1.statsinfo.value('@SamplingPercent', 'float'),
      LastUpdate        = x1.statsinfo.value('@LastUpdate', 'datetime2(7)')
    FROM sys.dm_exec_query_stats qs
    CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp
    CROSS APPLY qp.query_plan.nodes('//OptimizerStatsUsage/StatisticsInfo') x1(statsinfo)
    WHERE qs.query_plan_hash = @QueryPlanHash;