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:

1sp_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:

 1CREATE PROCEDURE usp_reindexAllTablesinAllDBs
 2AS
 3    DECLARE @SQL varchar(8000) -- if you use nvarchar for whack table names, change this to 4000
 4    SET @SQL = ''
 5
 6    SELECT @SQL = @SQL + 'EXEC ' + NAME + '..sp_MSforeachtable @command1=''DBCC DBREINDEX (''''*'''')'', @replacechar=''*''' + Char(13)
 7    FROM MASTER..Sysdatabases
 8    WHERE NAME != 'tempdb'
 9
10    PRINT @SQL
11    EXEC (@SQL)
12GO

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.

Editor’s note (2025): DBCC DBREINDEX and the sp_msforeach* procedures are deprecated/undocumented and can be unreliable. For current versions of SQL Server, prefer looping over sys.databases/sys.tables yourself and using ALTER INDEX ... REBUILD/REORGANIZE as appropriate. See Microsoft Docs for ALTER INDEX: https://learn.microsoft.com/sql/t-sql/statements/alter-index-transact-sql