SQL Server looks at index fragmentation and defragments it

--Step 1: Find indexes with fragmentation greater than a certain threshold (here the threshold is 90)

SELECT OBJECT_NAME(ind.OBJECT_ID) AS TableName,
    ind.name AS IndexName,
    indexstats.index_type_desc AS IndexType,
    indexstats.avg_fragmentation_in_percent 
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) indexstats 
    INNER JOIN sys.indexes ind ON ind.object_id = indexstats.object_id AND ind.index_id = indexstats.index_id 
WHERE indexstats.avg_fragmentation_in_percent > 90 
ORDER BY indexstats.avg_fragmentation_in_percent DESC

operation result

--Step 2: Reorganize the index (copy the table name TableName in step 1 and adjust the threshold)

ALTER INDEX ALL ON [TableName] 
REBUILD WITH (FILLFACTOR = 90, SORT_IN_TEMPDB = ON,STATISTICS_NORECOMPUTE = ON); 

Reference:How to check the index fragmentation of SQL Server and sort it out - Code Pioneer Network

Guess you like

Origin blog.csdn.net/a497785609/article/details/133901803