Labels

Tuesday 16 February 2021

Get Indexfragmentation details for all databases in a SQL Server instance

 

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
GO

DECLARE @Tbl TABLE (
	ServerName VARCHAR(128)
	,DBName VARCHAR(128)
	,SchemaName VARCHAR(128)
	,TableName VARCHAR(100)
	,IndexName VARCHAR(100)
	,FragPercent FLOAT
	,IndexType TINYINT
	,IsPrimaryKey BIT
	);

INSERT INTO @Tbl
EXEC SP_MSforeachdb @command1 = 'use [?];
                select  @@Servername, 
                        DB_NAME(),
                        sc.name as SchemaName,
                        object_name (s.object_id) as TableName, 
                        I.name, 
                        s.avg_fragmentation_in_percent, 
                        I.type, 
                        I.is_primary_key
                from sys.dm_db_index_physical_stats (DB_ID (), NULL, NULL, NULL, ''LIMITED'') as S
                    join sys.indexes as I on s.object_id = I.object_id and s.index_id = I.index_id
                    join sys.objects as O on s.object_id = O.object_id 
                    join sys.schemas as sc on O.schema_id = sc.schema_id
                where o.type = ''U'' and avg_fragmentation_in_percent > 20 and (I.name is not null) 
                ORDER BY  avg_fragmentation_in_percent DESC'

SELECT *
FROM @Tbl
GO