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:
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
CREATE PROCEDURE usp_reindexAllTablesinAllDBs
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’
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.