Tuesday, June 7, 2011

MSSQL: Optimize Table(s) (Like in MySQL)

To optimize one table in database:

ALTER INDEX all ON [table name] REORGANIZE
exp.:
ALTER INDEX all ON people REORGANIZE

To optimize all tables in entire database:
USE [databaseName]
EXEC sp_MSforeachtable @command1="ALTER INDEX all ON ? REORGANIZE"

or

EXEC [databaseName].dbo.sp_MSforeachtable @command1="ALTER INDEX all ON ? REORGANIZE"

This works only in MSSQL 2005 and later.

It is not the same as MySQL optimize.