Sometimes, you just need a quick and to the point script to rebuild or reorganize (defragment) all of the indexes in all of the tables of your SQL Server database. Well, here it is:
How it works
This script will loop through all of the tables in a given SQL Server database, create the REBUILD or REORGANIZE statement indicating “All” for the index name and then execute the statement. Simple!
Please note that I’m not generally a fan of using cursors in code but this is one of the few exceptions. The reason this is an exception is because this is a maintenance script meant to be run by one person at a time and 99% of the work happens outside of the cursor. In *nearly* all cases, it is possible to write a query without the use of cursors (technically this could be as well) but for this particular script it just reads better with the use of a cursor.
One other note regarding cursors – If you must use a cursor, please always specify the “LOCAL” & “FAST_FORWARD” options. This controls the scope of your cursor (to just be local) and the direction your cursor can move (just looping forward).
Okay – well I’m off my soapbox about cursors now so enjoy your freshly rebuilt (or reorganized) indexes and let me know if you have any questions!
Filed under: SQL Server 2008, SQL Server 2012, SQL Server Programming, T-SQL Tagged: ALTER INDEX, Defragment Index, Indexes, Rebuild Index, Reorganize Index, SQL Server Image may be NSFW.
Clik here to view.

Clik here to view.
