Automatically re-indexing all the tables in a database, SQL Server

While analyzing performance of application, many a times we find that indexes are broken, not rebuild from a long time and that is hampering performance. We need to quickly re-index all the tables in a SQL server. This is a script for rebuilding all indexes in given database.
 
DECLARE @TableName varchar(255)
DECLARE TableCursor CURSOR FOR
                 SELECT table_name
                          FROM information_schema.tables
                                  WHERE table_type = ‘base table’
              OPEN TableCursor
              FETCH NEXT FROM TableCursor
              INTO @TableName
              WHILE @@FETCH_STATUS = 0
             BEGIN
                     DBCC DBREINDEX(@TableName,,90)
                     FETCH NEXT FROM TableCursor
                     INTO @TableName
             END
            CLOSE TableCursor
DEALLOCATE TableCursor
 
Please note that  DBREINDEX is not supported for use on the following objects:
  • System tables
  • Spatial indexes
  • xVelocity memory optimized columnstore indexes

www.HyperSmash.com

2 thoughts on “Automatically re-indexing all the tables in a database, SQL Server

  1. Wow, that’s what I was seeking for, what a stuff! present here at this blog, thanks admin of this web page.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.