Duty Free!!

SQL Write-Ahead Overhead…

SQL Server: Rebuild Indexes based on Fragmentation.

In the recent past there were quiet a few friends of mine asking

for a script to rebuild indexes selectively-based on Defragmentation.


is a nice discussion for this kinda script. The script listed by ‘thomas’

is  a good/simple one.One thing this script doesnt do, is rebuilding

indexes on a View in SQL 2005. This can be attained by a small change

– try changing the

“so.type =’U'” to “so.type in (‘U’,’V’)”.

Also, this script does an offline operation, Reindexing. Inorder to have

this  changed to Defragment, which is an online operation, change the code

SELECT @execstr = ‘DBCC DBREINDEX (‘ + RTRIM(@tablename) + ‘,
‘ + RTRIM(@indexname) + ‘) WITH NO_INFOMSGS’


SELECT @execstr = ‘DBCC INDEXDEFRAG ( 0’ + RTRIM(@tablename) + ‘,
‘ + RTRIM(@indexname) + ‘) WITH NO_INFOMSGS’
SELECT (@execstr)
EXEC (@execstr)

SELECT @execstr = ‘UPDATE STATISTICS ON ‘ + RTRIM(@tablename) + ‘.
‘ + RTRIM(@indexname) + ‘ WITH FULLSCAN’

Remember that Reindexing will update the statistics while the

Indexdefrag doesnt. Hence it was explicitly provided with an update

statistics step in the above snippet.  Hope this helps!!


September 25, 2008 - Posted by | SQL Server

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: