Quantcast
Channel: SQL Steve » SQL Server 2008
Viewing all articles
Browse latest Browse all 20

How to: Rebuild or Reorganize All Indexes in a SQL Server database

$
0
0

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:

–Disable row counting
SETNOCOUNTON
–Define the cursor to loop through the user tables
DECLARETableCursorCURSORLOCALFAST_FORWARD
FOR
    SELECT
        QUOTENAME(TABLE_SCHEMA)+‘.’+QUOTENAME(TABLE_NAME)ASTableName
    FROM
        INFORMATION_SCHEMA.TABLES
    WHERE
        TABLE_TYPE=‘BASE TABLE’
    ORDERBY
        TableName
–Open the cursor
OPENTableCursor
–Create a variable to hold the table name and fetch the first row from the cursor
DECLARE@TableNameNVARCHAR(500)
FETCHNEXTFROMTableCursorINTO@TableName
–Loop
WHILE@@FETCH_STATUS= 0
BEGIN
    –Create the rebuild command
    DECLARE@CommandNVARCHAR(1000);
    SET@Command=‘ALTER INDEX ALL ON ‘+@TableName+‘ REBUILD WITH (SORT_IN_TEMPDB = ON, ONLINE = OFF)’
    SET@Command=‘ALTER INDEX ALL ON ‘+@TableName+‘ REORGANIZE WITH (LOB_COMPACTION = ON)’
    –Send feedback to the user
    RAISERROR(‘Executing: %s’, 10, 1,@Command)WITHNOWAIT
    –Execute the command
    execsp_executesql@Command
   
    –Fetch the next row from the cursor
    FETCHNEXTFROMTableCursorINTO@TableName
END
–Notify user that rebuild is complete
RAISERROR(‘ALL INDEXES PROCESSED’, 10, 1)WITHNOWAIT
GO

 

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

Viewing all articles
Browse latest Browse all 20

Trending Articles