提问人:Calkins 提问时间:11/16/2023 最后编辑:XedniCalkins 更新时间:11/16/2023 访问量:47
从“show execution plan xml”获取查询中使用的索引列表
Get list of used indexes in query from 'show execution plan xml'
问:
如何通过查询从已用索引的执行计划xml列表中获取?
我尝试了以下查询
SELECT DISTINCT
ExecutionPlan.value('(//@Index)[1]', 'NVARCHAR(MAX)') AS UsedIndex
FROM @ExecutionPlan.nodes('//IndexSeek/Object') AS ExecutionPlans(ExecutionPlan)
UNION
-- Find indexes used in IndexScan operations
SELECT DISTINCT
ExecutionPlan.value('(//@Index)[1]', 'NVARCHAR(MAX)') AS UsedIndex
FROM @ExecutionPlan.nodes('//IndexScan/Object') AS ExecutionPlans(ExecutionPlan);
答:
1赞
Xedni
11/16/2023
#1
XML 查询计划中有一个命名空间,在执行查询时需要引用该命名空间。试试这个:
;with xmlnamespaces(default 'http://schemas.microsoft.com/sqlserver/2004/07/showplan')
SELECT DISTINCT
ExecutionPlan.value('@Index', 'NVARCHAR(130)') AS UsedIndex
FROM @ExecutionPlan.nodes('//IndexScan/Object') AS ExecutionPlans(ExecutionPlan)
UNION
---- Find indexes used in IndexScan operations
SELECT DISTINCT
ExecutionPlan.value('@Index', 'NVARCHAR(130)') AS UsedIndex
FROM @ExecutionPlan.nodes('//IndexSeek/Object') AS ExecutionPlans(ExecutionPlan);
请注意,我假设您的查询计划中的 XML 命名空间与我的 XML 命名空间相同。也许仔细检查您的 XML 并确保它声明的 URL 与我提供的 URL 匹配xmlns
评论
0赞
Xedni
11/16/2023
@Calkins 考虑将此标记为答案,以帮助其他人更轻松地确定解决方案。
2赞
Caleb Carl
11/16/2023
#2
一个非常简单的解决方案如下 -
DECLARE @ExecutionPlan XML;
SELECT TOP 1
@ExecutionPlan = y.query_plan
FROM sys.dm_exec_query_stats AS x
CROSS APPLY sys.dm_exec_query_plan(x.plan_handle) AS y
ORDER BY x.last_execution_time DESC;
WITH XMLNAMESPACES
(
DEFAULT N'http://schemas.microsoft.com/sqlserver/2004/07/showplan'
)
SELECT DISTINCT
RelOp.typ.value(N'@PhysicalOp', N'sysname') AS operation
, Obj.typ.value(N'@Index', N'sysname') AS index_name
, Obj.typ.value(N'@Table', N'sysname') AS table_name
FROM @ExecutionPlan.nodes(N'//RelOp') RelOp(typ)
CROSS APPLY RelOp.typ.nodes(N'IndexScan/Object') Obj(typ)
这将提供表名、索引名和操作类型。下面的一个例子是 -
operation index_name table_name
----------------------- ------------------ ----------------
Clustered Index Seek [PK_ProductID] [Product]
Index Seek [UQIDX_SN] [ProductHistory]
评论