Find Fragmented Tables Quickly with DBCC SHOWCONTIG
Submitted by Andy on Mon, 05/02/2005 - 00:00.
Tagged: SQL Server 2000
• T-SQL
Using the below T-SQL, you can narrow the results of fragment tables within the current database. The data is obtained by running DBCC SHOWCONTIG on all tables, and the results is ordered by the the Number of Pages x Scan Density, descending.
DECLARE @min_pages int
DECLARE @max_scandensity decimal
SET @min_pages = 10
SET @max_scandensity = 95.0
-- Create showcontig temp table
CREATE TABLE #tmp_frag (
ObjectName sysname COLLATE database_default NOT NULL, ObjectId int,
IndexName sysname COLLATE database_default NULL, 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)
-- Get showcontig for all tables
INSERT INTO #tmp_frag
EXEC('DBCC SHOWCONTIG WITH TABLERESULTS, NO_INFOMSGS')
-- Filter results
SELECT ObjectName, CountPages, ScanDensity
FROM #tmp_frag
WHERE CountPages >= @min_pages
AND ScanDensity <= @max_scandensity
ORDER BY CountPages * (100 - ScanDensity) DESC
-- Cleanup
TRUNCATE TABLE #tmp_frag
DROP TABLE #tmp_frag
