我有一个存储过程,该存储过程在给定碎片阈值@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,我如何引用它们以重建它们?