我正在运行以下查询以获取索引外部碎片:
SELECT SCH.[name] as 'Schema'
,TBL.[name] as 'Table'
,IX.[name] as 'Index'
,IXStats.[avg_fragmentation_in_percent]
,IXStats.[page_count]
FROM [sys].[dm_db_index_physical_stats] (DB_ID(), NULL, NULL, NULL, NULL) AS IXStats
INNER JOIN [sys].[tables] AS TBL
on TBL.[object_id] = IXStats.[object_id]
INNER JOIN [sys].[schemas] SCH
on TBL.[schema_id] = SCH.[schema_id]
INNER JOIN [sys].[indexes] AS IX
ON IX.[object_id] = IXStats.[object_id]
AND IXStats.[index_id] = IX.[index_id]
WHERE IXStats.database_id = DB_ID()
ORDER BY IXStats.[avg_fragmentation_in_percent] DESC
对于几个表(没有索引或主键),查询返回碎片。
这怎么可能? SQL Server是否创建了一些内部索引?
答案 0 :(得分:1)
因此,如果您运行查询并抓住index_id列,那么:
SELECT SCH.[name] as 'Schema'
,TBL.[name] as 'Table'
,IX.[name] as 'Index'
,IX.index_id
,IXStats.[avg_fragmentation_in_percent]
,IXStats.[page_count]
FROM [sys].[dm_db_index_physical_stats] (DB_ID(), NULL, NULL, NULL, NULL) AS IXStats
INNER JOIN [sys].[tables] AS TBL
on TBL.[object_id] = IXStats.[object_id]
INNER JOIN [sys].[schemas] SCH
on TBL.[schema_id] = SCH.[schema_id]
INNER JOIN [sys].[indexes] AS IX
ON IX.[object_id] = IXStats.[object_id]
AND IXStats.[index_id] = IX.[index_id]
WHERE IXStats.database_id = DB_ID()
ORDER BY IXStats.[avg_fragmentation_in_percent] DESC
您应该看到没有为它们定义索引的表的ID为0,这意味着该表是一个堆(即没有聚簇索引的表)。如果您看到索引ID为1,则表示该表是聚簇索引。
有关堆的更多信息,请参阅此处: