Reindex All Tables in a Database

I just wanted to share a quick script that I used to help re-index all the tables in my database. If you have any questions about it, please let me know!

DECLARE @TableName varchar(255)


WHERE TABLE_TYPE = 'base table'

OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @TableName
		PRINT 'Reindexing: ' + @TableName
		DBCC DBREINDEX(@TableName,' ',90)
		FETCH NEXT FROM TableCursor INTO @TableName
CLOSE TableCursor

By Shannon Lowder

Shannon Lowder is the Database Engineer you've been looking for! Look no further for expertise in: Business Analysis to gather the business requirements for the database; Database Architecting to design the logical design of the database; Database Development to actually build the objects needed by the business logic; finally, Database Administration to keep the database running in top form, and making sure there is a disaster recovery plan.


  1. Shannon,

    What are the pros and cons of this script. Basically, I want to know if I can run this script blindly whenever I see a performance (slowness) issues.

    1. I wouldn’t run it blindly. This is more for a proactive situation. If you know you get a lot of reads on your tables, and you also do a lot of inserting, you may find your indexes grow really fragmented. You could either put in a maintenance plan to handle it, or you could use this script.

      I shared the script because I was in a situation where I needed to re-index everything as quickly as I could…. and this was the script that came from that.

      Email me at [email protected], we can talk about your specific situation and I can give you a few hints of things to try every time.

        1. I usually follow Michelle Ufford’s indexing stragegies her latest script can be found here. If the fragmentation is over 30, just rebuild the index, the cost should be lower than trying to re-organize. In the past I recall anything less than 5% fragmentation should be ignored, but it looks like Michelle has upped that threshold to 10%. I would say if you have the time in your maintenance window to rebuild those indexes between 5 and 30%, go for it. If not, I’d sacrifice rebuilding the 5% fragmentation indexes before sacrificing those with more fragmentation.

          When you start getting tables with BILLIONS of rows, you might want to consider something a little more drastic. I start partitioning the data either with actual partitioning, or adding where clauses to my indexes, so I can rebuild sub-sets of the indexes more quickly.

Leave a comment

Your email address will not be published. Required fields are marked *