SQL Server 索引碎片清理
查看碎片
SELECT DB_NAME() AS DatbaseName ,
SCHEMA_NAME(o.Schema_ID) AS SchemaName ,
OBJECT_NAME(s.[object_id]) AS TableName ,
i.name AS IndexName ,
ROUND(s.avg_fragmentation_in_percent, 2) AS [Fragmentation %] ,
CASE WHEN avg_fragmentation_in_percent > 30 THEN '严重碎片,索引需要重建'
WHEN avg_fragmentation_in_percent >= 5
AND avg_fragmentation_in_percent < 30 THEN '轻度碎片,索引需要重新组织'
ELSE '正常状态'
END 提示
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) s
INNER JOIN sys.indexes i ON s.[object_id] = i.[object_id] AND s.index_id = i.index_id
INNER JOIN sys.objects o ON i.object_id = O.object_id
ORDER BY [Fragmentation %] DESC
清理碎片
///用DBCC查看扫描密度
dbcc showcontig(@table_id)
这里可以看到扫描密度最佳计数和实际计数差别还是比较大的。并且逻辑扫描碎片达到99%
执行数据库表索引重建
DBCC DBREINDEX('bs_TestResultRecord')