/*==========================================================================

Purpose: To find tables with large logical fragmentation and generate a 

script to alter the fill factor   

 

Author: Carolyn Richardson 
Date: 24/09/2007 

==========================================================================*/

 
CREATE TABLE #dbshowcontig 
                
fid intidentity(1,1), 
                
[timestamp] datetime DEFAULT GETDATE(), 
                
ObjectName sysname
                
ObjectId INT
                
IndexName sysname
                
IndexId INT
                
[Level] INT
                
Pages INT
                
[Rows] INT
                
MinimumRecordSize INT
                
MaximumRecordSize INT
                
AverageRecordSize float
                
ForwardedRecords INT
                
Extents INT
                
ExtentSwitches INT
                
AverageFreeBytes float
                
AveragePageDensity float
                
ScanDensity float
                
BestCount INT
                
ActualCount INT
                
LogicalFragmentation float
                
ExtentFragmentation float
    ) 
GO 
INSERT INTO #dbshowcontig ([ObjectName], [ObjectId], [IndexName]

[IndexId][Level], [Pages], [Rows], [MinimumRecordSize], [MaximumRecordSize],

[AverageRecordSize], [ForwardedRecords], [Extents], [ExtentSwitches],

[AverageFreeBytes], [AveragePageDensity], [ScanDensity], [BestCount],

[ActualCount], [LogicalFragmentation],[ExtentFragmentation])

 

EXEC('DBCC showcontig WITH tableresults, no_infomsgs'

 

SELECT'DBCC DBREINDEX ('+name+', '''', 80) WITH NO_INFOMSGS' 
    
FROM sysobjects 
    
WHERE xtype ='U' 
        
AND id IN 
    
SELECT CAST(objectid AS VARCHAR(100)) 
        
FROM #dbshowcontig 
        
WHERE CAST(LogicalFragmentation AS INT) > 30
    
--Gives the script you need, adjust as appropriate 



 
DROP TABLE #dbshowcontig