Show table index fragmentation in T-SQL.

select t1.object_id,
    OBJECT_NAME(t1.object_id) as ObjectName,
    t2.fill_factor,
    t2.name,
    index_type_desc,
    avg_fragmentation_in_percent,
    avg_record_size_in_bytes,
    'ALTER INDEX ALL ON dbo.' + OBJECT_NAME(t1.object_id) + ' REBUILD WITH (FILLFACTOR = 80, SORT_IN_TEMPDB = ON, STATISTICS_NORECOMPUTE = ON); RAISERROR (N''Indexes rebuilt succesfully on ' + OBJECT_NAME(t1.object_id) + ''', 10, 1, 1) WITH NOWAIT;' as RebuildScript
from sys.dm_db_index_physical_stats(DB_ID(), null, null, null , null) t1
    nner join sys.indexes t2 on t1.object_id = t2.object_id and t1.index_id = t2.index_id
where avg_fragmentation_in_percent > 20
order by 2 desc;