From 86013114946ac34ec1d7e9bd933c7163f57aa056 Mon Sep 17 00:00:00 2001 From: aarunreddy <66240041+aarunreddy@users.noreply.github.com> Date: Tue, 16 Sep 2025 11:19:13 -0700 Subject: [PATCH] Create Index_Fragmentation_on_DB Find the indexes on a database which are fragmented more than 30% and will provide script as well in Script column. --- Scripts/Index_Fragmentation_on_DB | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Scripts/Index_Fragmentation_on_DB diff --git a/Scripts/Index_Fragmentation_on_DB b/Scripts/Index_Fragmentation_on_DB new file mode 100644 index 00000000..9c6373e0 --- /dev/null +++ b/Scripts/Index_Fragmentation_on_DB @@ -0,0 +1,20 @@ +/** +Author: Arun Agunuru +Find the indexes on a database which are fragmented more than 30% and will provide script as well in Script column. +**/ +use database +go +SELECT dbschemas.[name] as 'Schema', +dbtables.[name] as 'Table', +dbindexes.[name] as 'Index', +indexstats.alloc_unit_type_desc, +indexstats.avg_fragmentation_in_percent, +indexstats.page_count, +'ALTER INDEX [' + dbindexes.[name] + '] ON ['+dbschemas.[name] +'].['+dbtables.[name]+ '] REBUILD PARTITION = ALL WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)' as Script --provide the script to pickup and execute +FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS indexstats +INNER JOIN sys.tables dbtables on dbtables.[object_id] = indexstats.[object_id] +INNER JOIN sys.schemas dbschemas on dbtables.[schema_id] = dbschemas.[schema_id] +INNER JOIN sys.indexes AS dbindexes ON dbindexes.[object_id] = indexstats.[object_id] +AND indexstats.index_id = dbindexes.index_id +WHERE indexstats.database_id = DB_ID() and indexstats.avg_fragmentation_in_percent >= 30 and dbindexes.[name] is NOT NULL +ORDER BY indexstats.avg_fragmentation_in_percent desc