Listing 1: Query to defragment only the indexes that need it CREATE PROCEDURE [dbo].[rebuild_indexes_by_db] @DBName NVARCHAR(128) -- Name of the db , @ReorgLimit TINYINT = 15 -- Minimum fragmentation % to use Reorg method , @RebuildLimit TINYINT = 30 -- Minimum fragmentation % to use Rebuild method , @PageLimit SMALLINT = 10 -- Minimum # of Pages before you worry about it , @SortInTempdb TINYINT = 0 -- 1 = Sort in tempdb option , @OnLine TINYINT = 0 -- 1 = Online Rebuild, Reorg is ignored , @ByPartition TINYINT = 1 -- 1 = Treat each partition separately , @LOBCompaction TINYINT = 1 -- 1 = Always do LOB compaction , @DoCIOnly TINYINT = 0 -- 1 = Only do Clustered indexes , @UpdateStats TINYINT = 1 -- 1 = Update the statistics on Reorgs , @MaxDOP TINYINT = 0 -- 0 = Default so omit this from the statement , @ExcludedTables NVARCHAR(MAX) = '' -- Comma delimited list of tables (DB.Schema.Table) to exclude from processing