Search code examples
sqlsql-serverindexingrebuildreindex

Rebuilding Indexes with Scripts


I'm looking for help modifying the following script or at least making sure it's correct to rebuild the indexes on a table in my database called SearchTable. I'm brand new to SQL and I don't want to destroy anything.

SELECT 'ALTER INDEX ALL ON ' + MyDatabaseName.[SearchTable] + ' REBUILD; '
  FROM INFORMATION_SCHEMA.TABLES t
 WHERE t.[TABLE_TYPE] = 'BASE TABLE'

Solution

  • Easiest and safest way is to create a Maintenance Plan.

    Expand Management in the Object Explorer> Right click Maintenance Plans> Maintenance Wizard> Create Plan for Rebuilding Indexes.

    Should be straight forward. It eventually makes a Job in your server agent and then you can set a schedule or run the job manually by running this script

    EXEC msdb..sp_start_job N'NAME OF JOB'
    

    Maintenance Plan Wizard

    One thing to remember when using this technique. If you delete any tables after you create the Job/Maintenance Plan, the Plan needs to be modified to not include any deleted tables. If you don't do this, the Job will Fail. To make Edits you need to access Management Studio from the actual server. You cant modify Maintenance Plans remotely.

    To get more information on whether the Maintenance Plan succeeded or not you can

    Right Click on Maintenance Plans > View History