Monday, January 4, 2010

SQL Server 2005 - Performance optimization with DMV

After reading a very interesting article on SQL Server 2005 optimization with DMVs, I want to share a sql script to identify the indexes (in a specific database used) that are very logically fragmented (i.e., require rebuild or reorganization to improve performance of sql queries). See details below:
-----------------------------------------------------------------------
/*
------------------------------------------------------
Purpose: Identifying Most Logically Fragmented Indexes
------------------------------------------------------
Details:
------------------------------------------------------
Logical index fragmentation indicates the percentage
of entries in the index that are out of order.
This is not the same as the page-fullness type of fragmentation.
Logical fragmentation has an impact on any order scans
that use an index. When possible, this fragmentation should be removed.
This can be achieved with a rebuild or reorganization of the index.
You can identify the most logically fragmented indexes using
the sys.dm_db_index_physical_stats DMV, which
lets you view details about the size and fragmentation of indexes.
This is joined to the sys.indexes DMV,
which contains details used in the creation of the index.
This script identifies the most logically fragmented indexes.
The results, which are sorted by the percent of fragmentation,
show the most logically fragmented indexes, and the database/table.
------------------------------------------------------
*/
DECLARE @dbid int;
select @dbid = db_id();
SELECT
DatabaseName = DB_NAME()
,TableName = OBJECT_NAME(s.[object_id])
,IndexName = i.name
,[Fragmentation %] = ROUND(avg_fragmentation_in_percent,2)
INTO #TempFragmentation
FROM sys.dm_db_index_physical_stats(@dbid,null, null, null,'DETAILED') s
INNER JOIN sys.indexes i ON s.[object_id] = i.[object_id]
AND s.index_id = i.index_id
WHERE s.database_id = @dbid
AND i.name IS NOT NULL -- Ignore HEAP indexes.
AND OBJECTPROPERTY(s.[object_id], 'IsMsShipped') = 0
AND avg_fragmentation_in_percent > 1
ORDER BY [Fragmentation %] DESC;

SELECT *
INTO Admin.dbo.[Most Logically Fragmented Indexes]
FROM #TempFragmentation
ORDER BY [Fragmentation %] DESC;
DROP TABLE #TempFragmentation;

---------------------------------------------------------------------------
For more information, check out the white paper on Performance Tuning Waits Queues.doc
---------------------------------------------------------------------------
For SQL Server 2008 DMV views click here

No comments: