SQL Server: Identify And Defragment Indexes Using DBCC SHOWCONTIG & DBCC INDEXDEFRAG

A good defrag script is worth its weight in gold. This time, I copied this from Microsoft and am shamelessly posting it here because I don’t know when MS will bury it somewhere where it cannot be located anymore!

Just because you de-fragmented does not actually mean that it did it! It means, it tried. If you query again, you may find indexes above your fragmentation threshold for reorganization. If that is the case, you are better off rebuilding indexes (online preferable). You have to be careful when rebuilding as you could accidentally turn-off features that are on an index already, like compression.

Source:

https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-indexdefrag-transact-sql

Again, this was copied from MS documentation (link is above) and is not my original work!

Set the threshold percent before you run. 50 is a good number (script defaults to 30).

/*Perform a 'USE <database name>' to select the database in which to run the script.*/
-- Declare variables
SET NOCOUNT ON;
DECLARE @tablename varchar(255);
DECLARE @execstr   varchar(400);
DECLARE @objectid  int;
DECLARE @indexid   int;
DECLARE @frag      decimal;
DECLARE @maxfrag   decimal;  

-- Decide on the maximum fragmentation to allow for.
SELECT @maxfrag = 30.0;  

-- Declare a cursor.
DECLARE tables CURSOR FOR
   SELECT TABLE_SCHEMA + '.' + TABLE_NAME
   FROM INFORMATION_SCHEMA.TABLES
   WHERE TABLE_TYPE = 'BASE TABLE';  

-- Create the table.
CREATE TABLE #fraglist (
   ObjectName char(255),
   ObjectId int,
   IndexName char(255),
   IndexId int,
   Lvl int,
   CountPages int,
   CountRows int,
   MinRecSize int,
   MaxRecSize int,
   AvgRecSize int,
   ForRecCount int,
   Extents int,
   ExtentSwitches int,
   AvgFreeBytes int,
   AvgPageDensity int,
   ScanDensity decimal,
   BestCount int,
   ActualCount int,
   LogicalFrag decimal,
   ExtentFrag decimal);  

-- Open the cursor.
OPEN tables;  

-- Loop through all the tables in the database.
FETCH NEXT
   FROM tables
   INTO @tablename;  

WHILE @@FETCH_STATUS = 0
BEGIN
-- Do the showcontig of all indexes of the table
   INSERT INTO #fraglist
   EXEC ('DBCC SHOWCONTIG (''' + @tablename + ''')
      WITH FAST, TABLERESULTS, ALL_INDEXES, NO_INFOMSGS');
   FETCH NEXT
      FROM tables
      INTO @tablename;
END;  

-- Close and deallocate the cursor.
CLOSE tables;
DEALLOCATE tables;  

-- Declare the cursor for the list of indexes to be defragged.
DECLARE indexes CURSOR FOR
   SELECT ObjectName, ObjectId, IndexId, LogicalFrag
   FROM #fraglist
   WHERE LogicalFrag >= @maxfrag
      AND INDEXPROPERTY (ObjectId, IndexName, 'IndexDepth') > 0;  

-- Open the cursor.
OPEN indexes;  

-- Loop through the indexes.
FETCH NEXT
   FROM indexes
   INTO @tablename, @objectid, @indexid, @frag;  

WHILE @@FETCH_STATUS = 0
BEGIN
   PRINT 'Executing DBCC INDEXDEFRAG (0, ' + RTRIM(@tablename) + ',
      ' + RTRIM(@indexid) + ') - fragmentation currently '
       + RTRIM(CONVERT(varchar(15),@frag)) + '%';
   SELECT @execstr = 'DBCC INDEXDEFRAG (0, ' + RTRIM(@objectid) + ',
       ' + RTRIM(@indexid) + ')';
   EXEC (@execstr);  

   FETCH NEXT
      FROM indexes
      INTO @tablename, @objectid, @indexid, @frag;
END;  

-- Close and deallocate the cursor.
CLOSE indexes;
DEALLOCATE indexes;  

-- Delete the temporary table.
DROP TABLE #fraglist;
GO
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s