Оптимизация индексов mssql вариант 2

select OBJECT_NAME(object_id) object_name, (select name from sys.indexes i where i.object_id = pi.object_id and i.index_id = pi.index_id) as index_name, ( 'ALTER INDEX ['+ (select name from sys.indexes i where i.object_id = pi.object_id and i.index_id = pi.index_id)+ '] ON [dbo].['+ OBJECT_NAME(object_id)+ '] REBUILD WITH (SORT_IN_TEMPDB = ON);'+ ' -- avg frag='+cast(pi.avg_fragmentation_in_percent as nvarchar)+'%' ) as rebuild_sql, * FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) pi WHERE avg_fragmentation_in_percent > 2 and index_type_desc not in ( 'HEAP' ) order by avg_fragmentation_in_percent desc ; --select * from sys.indexes i where i.object_id = 248492064;