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 Cloud and Datacenter Management & Data Platform MVP who has worked in IT for over 20 years. She is the creator of the popular SQL PowerShell module dbatools, and holds a number of certifications, including those relating to SQL Server, Linux, SharePoint and network security. 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 *

*