T-SQL: Reindex All Indexes in All Databases (sans tempdb)

As you probably know, Microsoft provides two undocumented/unsupported stored procedures for iterating through databases, sp_msforeachdb and sp_msforeachtable. I’ve always wondered, then, why the following code never showed up in Google searches:

sp_MSforeachdb @command1 = 'EXEC sp_msForEachTable @COMMAND1= ''DBCC DBREINDEX ( "#")'', @replacechar=''#'''

Theoretically, this script should go to each database and reindex every table. Unfortunately, Microsoft used the same global cursor (hCForEach) in both which causes some data confusion. The script does iterate through each database but it attempts to reindex the first database’s table names over and over again, even if the same table name does not appear in subsequent databases. Upon researching this behavior, I found a great post at SQLTeam.com. In it, ToddV, a guy with some mad SQL skills shared code that’s similar to this

reindexAllTablesinAllDatabases.sql

CREATE PROCEDURE usp_reindexAllTablesinAllDBs
AS
DECLARE @SQL  varchar(8000) -- if you use nvarchar for whack table names, change this to 4000
SET @SQL = ''

SELECT @SQL = @SQL + 'EXEC ' + NAME + '..sp_MSforeachtable @command1=''DBCC DBREINDEX (''''*'''')'', @replacechar=''*''' + Char(13)
FROM MASTER..Sysdatabases where NAME !='tempdb'

PRINT @SQL
EXEC (@SQL)
GO

His procedure didn’t exclude tempdb and I ran into an error. Otherwise, it worked perfectly. If I remember correctly, reindexing clustered indexes causes the tables to lock up so consider running this script when it’s unlikely that anyone will be in the database.

Chrissy is a PowerShell MVP who has worked in IT for nearly 20 years, and currently serves as a Sr. Database Engineer in Belgium. Always an avid scripter, she attended the Monad session at Microsoft’s Professional Developers Conference in Los Angeles back in 2005 and has worked and played with PowerShell ever since. Chrissy is currently pursuing an MS in Systems Engineering at Regis University and helps maintain RealCajunRecipes.com in her spare time. She holds a number of certifications, including those relating to SQL Server, SuSE Linux, SharePoint and network security. She recently became co-lead of the SQL PASS PowerShell Virtual Chapter. You can follow her on Twitter at @cl.

Posted in SQL Server

Leave a Reply

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

*