I had to get this code somewhere I can find it later so here it is on my blog…aka my personal script folder. This code will parse a SQL Server XML Query Plan document if you have turned Trace Flag 8666 on. I won’t go into to much detail but turning on this trace flag allows you to see the statistical information SQL Server uses when it creates and execution plan. Fabiano Amorim has a more complete write up here. I could not find a way to search the sys.dm_exec_query_plan DMV in SQL Server 2008 R2 without getting a nasty error. So you have to Show the XML plan then save it to a file, or to SQL Server somehow then parse it. I choose the former so then I had to come up with some way to parse it. Here is my code written in PowerShell to dump out the DB, Schema, Table, and the affected statistic as well as the statistic column that is being used in the query plan. If anyone has a better way to do this I would love to see it.
[xml] $xml= gc .\QueryPlanXML.xml $xml.showPlanXML.BatchSequence.Batch.Statements.StmtSimple.QueryPlan.InternalInfo.EnvColl.Recompile | % {$_.Field| ?{$_.FieldName -eq 'wszDB' -or $_.FieldName -eq 'wszSchema' -or $_.FieldName -eq 'wszTable'}; $_.ModTrackingInfo| % {$_.Field}| ? {$_.FieldName -eq 'wszStatName' -or $_.FieldName -eq 'wszColName'}; '------------';} |