Automate INDEX rebuild based on fragmentation results?

后端 未结 4 1890
心在旅途
心在旅途 2021-02-02 00:26

Is it possible to add a maintenance job to check indexes fragmentation. If greater than 50% then rebuild those indexes automatically ?

Index size can vary from 100MB to

4条回答
  •  清歌不尽
    2021-02-02 00:53

    yes, you can.

    You can get the fragmented indexes using this query:

    SELECT OBJECT_NAME(i.OBJECT_ID) AS TableName,
    i.name AS IndexName,
    indexstats.avg_fragmentation_in_percent
    FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'DETAILED') indexstats
    INNER JOIN sys.indexes i ON i.OBJECT_ID = indexstats.OBJECT_ID
    AND i.index_id = indexstats.index_id
    WHERE indexstats.avg_fragmentation_in_percent > 20
    

    and based on the result just build a command to recreate them

    I would wrap everything on a Stored Procedure and call it from a SQL Server Job

    FYI, 50% is a very big fragmentation. I would go with less.

提交回复
热议问题