Fragmented Tables

By | June 16, 2019

This code will locate SQL tables with fragmentation:

--Replace DB_Name
USE DB_Name;  
GO  
SELECT OBJECT_NAME(a.OBJECT_ID)AS TableName, a.index_id, name, avg_fragmentation_in_percent,avg_page_space_used_in_percent,page_count  
FROM sys.dm_db_index_physical_stats(DB_ID(N'DB_Name'), NULL, NULL, NULL,'SAMPLED') AS a  
    JOIN sys.indexes AS b 
      ON a.object_id = b.object_id AND a.index_id = b.index_id
WHERE avg_fragmentation_in_percent >= 30
ORDER BY page_count DESC  
GO