我有一个存储过程在给定碎片阈值@FragmentationThresholdForReorganizeTableLowerLimit 的情况下检索具有高碎片的索引:
SELECT OBJECT_NAME(IPS.OBJECT_ID) AS [TableName],
avg_fragmentation_in_percent, SI.name [IndexName],
schema_name(ST.schema_id) AS [SchemaName], fill_factor
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL , NULL) IPS
JOIN sys.tables ST WITH (nolock) ON IPS.OBJECT_ID = ST.OBJECT_ID
JOIN sys.indexes SI WITH (nolock) ON IPS.OBJECT_ID = SI.OBJECT_ID AND
IPS.index_id = SI.index_id
WHERE ST.is_ms_shipped = 0
AND SI.name IS NOT NULL
AND avg_fragmentation_in_percent >= CONVERT(DECIMAL, @FragmentationThresholdForReorganizeTableLowerLimit)
ORDER BY avg_fragmentation_in_percent DESC
就我而言,@FragmentationThresholdForReorganizeTableLowerLimit 设置为 5.0。
然后我遍历所有检索到的索引,并根据 avg_fragmentation_in_percent 值使用以下命令执行 REORGANIZE 或 REBUILD:
ALTER INDEX [IndexName] ON [SchemaName].[Table] REORGANIZE
ALTER INDEX [IndexName] ON [SchemaName].[Table] REBUILD WITH (FILLFACTOR = 100, STATISTICS_NORECOMPUTE = OFF)
执行上述操作后,如果我执行以下查询以查找所有索引的平均碎片百分比,我可以看到 HEAP 类型的索引尚未重新组织/重建:
SELECT a.index_id, name, avg_fragmentation_in_percent, index_type_desc
FROM sys.dm_db_index_physical_stats (DB_ID(),
NULL, NULL, NULL, NULL) AS a
JOIN sys.indexes AS b
ON a.object_id = b.object_id AND a.index_id = b.index_id
WHERE avg_fragmentation_in_percent > '5.0'
ORDER BY a.avg_fragmentation_in_percent desc;
GO
下面是显示查询输出的屏幕截图:
那么为什么堆索引没有被重新组织/重建呢?我如何重新组织或重建它们以消除它们的碎片?
更新:对不起我的错误,事实上我没有重建堆索引,因为我在 where 子句中使用“AND SI.name IS NOT NULL”条件时丢弃了它们......
所以在堆索引的情况下,因为它们的名字是 NULL,我怎样才能引用它们来重建它们呢?