(Update: An ONLINE version of this procedure is now available)
I am sure we all have our own version of a "smart" reindex script for SQL Server 2000. This is a script that assesses the current level of fragmentation, and only executes a reindex or indexdefrag if the fragmentation falls below a certain threshold. In the 2000 world I have always preferred using "smart" index maintenance scripts for several reasons, including:
- Index defragmentation is a logged activity. By running a dbcc dbreindex on all indexes in your larger tables you can artificially inflate your transaction log.
- Address your index fragmentation can lock pages or tables (depending on how you decide to defrag your indexes). If your index is not heavily fragmented, you are needlessly locking resources and decreasing concurrency.
- Performing index maintenance on all indexes in a database can take much longer than necessary. With shrinking maintenance windows, this typically is not acceptable.
Well, SQL Server 2005 offers options to rebuild indexes without locking resources, or rebuild only a partition (although we are talking Enterprise features here). These are certainly improvements in index maintenance. Even so, we all need to continue to use "smart" index maintenance scripts. We should only address index fragmentation where it is necessary and not arbitrarily take the "easy" way out by running some sp_msforeachtable statement with a dbcc dbreindex parameter.
Attached is one that I have developed which is quite handy in a consolidated environment. In such an environment, one would prefer to have a single copy of a script and simply pass in a database name as a parameter to rebuild or reorganize indexes that are deemed "fragmented". I envision this type of environment would have a database that is designed for DBA scripts; I sometimes see people name these DBAStuff, DBAScripts, DBA, or the like.
The script accepts three parameters. The first parameter, @maxfrag, specifies the level of minimum level of fragmentation before the index must be rebuilt/reorganized. The parameter @maxdensity specifies the minimum average page fullness before the index must be rebuilt/reorganized. The final parameter @databasename allows you to specify which database you want to assess.
The beauty of this script is in the use of the new dynamic management view sys.dm_db_index_physical_stats (one of a few reasons that this script will not work in SQL Server 2000 or on a SQL Server 2005 database which has the compatibility mode set to 80). This dmv allows you to pass in a database id as a parameter and returns a slew of useful index information in a table format.
I hope that the attached gives you something from which to base your own scripts. Let me know your opinions, and if you find this practice useful and necessary.