SQL SERVER – Automatically Defrag indexes based on a given fragmentation percent

This script performs a reorganization of the indexes of the tables that have a percentage of fragmentation greater than a number that you can decide

DECLARE @sqlCommand nvarchar(max)

SELECT @sqlCommand = string_agg( CONVERT(NVARCHAR(max) ,'ALTER INDEX ALL ON ' + T.name + ' REORGANIZE'), ';' )
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS DDIPS
INNER JOIN sys.tables T on T.object_id = DDIPS.object_id
INNER JOIN sys.schemas S on T.schema_id = S.schema_id
INNER JOIN sys.indexes I ON I.object_id = DDIPS.object_id
AND DDIPS.index_id = I.index_id
WHERE DDIPS.database_id = DB_ID()
and I.name is not null
AND DDIPS.avg_fragmentation_in_percent > 0   --Here specify the fragmentation percent

EXEC (@sqlCommand)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s