
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)