select name, object_id from sys.tables where type = 'U' and ( name like 'tbl_PRD%' or name like 'fm%' or name like 'tbl_TPM%') order by name with stats as ( union all SELECT ( select t.name from sys.tables t where t.object_id = s.object_id ) tableName, ( select i.name from sys.indexes i where i.object_id = s.object_id and i.index_id = s.index_id ) indexName, s.avg_fragmentation_in_percent FROM sys.dm_db_index_physical_stats( DB_ID(N'FSLibrary_RPC'), OBJECT_ID(N'#name#'), NULL, NULL , 'LIMITED') s ) select *, 'alter index [' + indexName + '] on [' + tableName + '] reorganize;' as reorg from stats where avg_fragmentation_in_percent > 0 order by avg_fragmentation_in_percent desc