December 9, 2014 07:48 by
Peter
When you have performance problems in your MSSQL database, one of the first thing you must to verify is that the fragmentation. When the fragmentation is high, SQL Server has got the chance to both reorganize or rebuild indexes. You are able to detect index fragmentation by making use of Dynamic Management View (DMV) sys.dm_db_index_physical_stats and verify the avg_fragmentation_in_percent column.
Use [MyDB];
SELECT a.index_id, name, avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS a
JOIN sys.indexes AS b ON a.object_id = b.object_id
AND a.index_id = b.index_id
ORDER BY avg_fragmentation_in_percent DESC;
When the value avg_fragmentation_in_percent in among 5% and 30% you ought to perform a reorganize of your indexes, not really a total rebuild. A rebuild you simply need invoked when the fragmentation percentage is more than 30%. No action ought to be taken when the fragmentation proportion is lower than 5% and that is a standard level of fragmentation.
The code below can rebuild all indexes with default fill factor:
Use [MyDB];
EXEC sp_MSforeachtable
@command1="print '?'",
@command2="ALTER INDEX ALL ON ? REBUILD WITH (ONLINE=OFF)"
Hope this code will helps you!