Sql-Server
在記憶體的執行計劃中尋找缺失的索引
我有以下查詢,向我展示了 sql server 中記憶體的內容:
SELECT cp.objtype AS ObjectType, OBJECT_NAME(st.objectid,st.dbid) AS ObjectName, cp.usecounts AS ExecutionCount, st.TEXT AS QueryText, qp.query_plan AS QueryPlan FROM sys.dm_exec_cached_plans AS cp CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) AS qp CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) AS st WHERE 1=1 --AND OBJECT_NAME(st.objectid,st.dbid) = 'YourObjectName' AND query_plan IS NOT NULL ORDER BY ExecutionCount DESC
有沒有辦法可以查詢 queryPlan 欄位以查找失去的索引?
您可以嘗試執行以下腳本並從此處查找記憶體執行計劃中缺少的索引
SELECT qp.query_plan , total_worker_time/execution_count AS AvgCPU , total_elapsed_time/execution_count AS AvgDuration , (total_logical_reads+total_physical_reads)/execution_count AS AvgReads , execution_count , SUBSTRING(st.TEXT, (qs.statement_start_offset/2)+1 , ((CASE qs.statement_end_offset WHEN -1 THEN datalength(st.TEXT) ELSE qs.statement_end_offset END - qs.statement_start_offset)/2) + 1) AS txt , qp.query_plan.value('declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/showplan"; (/ShowPlanXML/BatchSequence/Batch/Statements/StmtSimple/QueryPlan/MissingIndexes/MissingIndexGroup/@Impact)[1]' , 'decimal(18,4)') * execution_count AS TotalImpact , qp.query_plan.value('declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/showplan"; (/ShowPlanXML/BatchSequence/Batch/Statements/StmtSimple/QueryPlan/MissingIndexes/MissingIndexGroup/MissingIndex/@Database)[1]' , 'varchar(100)') AS [DATABASE] , qp.query_plan.value('declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/showplan"; (/ShowPlanXML/BatchSequence/Batch/Statements/StmtSimple/QueryPlan/MissingIndexes/MissingIndexGroup/MissingIndex/@Table)[1]' , 'varchar(100)') AS [TABLE] FROM sys.dm_exec_query_stats qs cross apply sys.dm_exec_sql_text(sql_handle) st cross apply sys.dm_exec_query_plan(plan_handle) qp WHERE qp.query_plan.exist('declare default element namespace "http://schemas.microsoft.com/sqlserver/2004/07/showplan";/ShowPlanXML/BatchSequence/Batch/Statements/StmtSimple/QueryPlan/MissingIndexes/MissingIndexGroup/MissingIndex[@Database!="m"]') = 1 ORDER BY TotalImpact DESC
它在 sql server 2008 和 2012 中對我來說有點用,但你仍然需要檢查它是否像你在 sql server 2014 中看到的那樣工作。
還,
除了以上內容,我建議您閱讀Find what queries in the plan cache use a specific index,這是 Jonathan 的一個很棒的腳本,它確實有助於理解這些索引在記憶體中目前執行計劃中的使用情況。