Navigation

Thursday, May 13, 2010

How to reorganize all indexes in a database

The DBCC DBIndex command works on one table at a time.  If you need to run DBCC DBIndex on all the tables in a database you can use the script below.

USE myDatabase
DECLARE @table varchar(200)
DECLARE Cursor1 CURSOR FOR
SELECT table_name FROM information_schema.tables
WHERE table_type = 'base table'
OPEN Cursor1
FETCH NEXT FROM Cursor1 INTO @table
WHILE @@FETCH_STATUS = 0
BEGIN
DBCC DBREINDEX(@table,' ',90)
FETCH NEXT FROM Cursor1 INTO @table
END
CLOSE Cursor1
DEALLOCATE Cursor1

While this script will work the Alter Index Reorganize|Rebuild command is the recommended method moving forward.

No comments: