SELECT object_name(dt.object_id) 表名,
索引名称 ,dt.avg_fragmentation_in_percent AS
外部碎片,dt.avg_page_space_used_in_percent AS
内部碎片
FROM
(
SELECT object_id,index_id,avg_fragmentation_in_percent,avg_page_space_used_in_percent
FROM sys.dm_db_index_physical_stats(
db_id('PMDB2021'),null,null,null,'DETAILED'
)
WHERE index_id <> 0
) AS dt
INNER JOIN si ON si.object_id=dt.object_id
AND si.index_id=dt.index_id
where dt.avg_fragmentation_in_percent>10
AND dt.avg_page_space_used_in_percent<75
ORDER BY avg_fragmentation_in_percent DESC
(1)当ExternalFragmentation > 10时说明出现了外部索引碎片。
(2)当InternalFragmentation < 75时说明出现了内部索引碎片。
上面我们分析索引碎片以及判定索引碎片的规则,那么我们又该如何进行磁盘索引碎片整理呢?如下有两种方式,我们接着往下讲。
(1)通过如下代码重组磁盘索引碎片
ALTER INDEX ALL ON TableName REORGANIZE
(2)通过如下代码重建磁盘索引碎片
ALTER INDEX ALL ON TableName REBUILD WITH (FILLFACTOR=90,ONLINE=ON)
--显示碎片
declare @table_id int
set @table_id=object_id('TB_GW_ProductPackInToGW')
--执行
dbcc showcontig(@table_id)
--以下是碎片整理
ALTER INDEX ALL ON TB_GW_CheckMaterialH REORGANIZE
ALTER INDEX ALL ON TB_GW_CheckMaterialH REBUILD WITH (FILLFACTOR=90,ONLINE=ON)