重建所有表中的所有索引,但需要排除某些表

时间:2019-01-07 12:25:29

标签: sql sql-server indexing sql-server-2012

我一直在寻找一种方法来重建所有表中的所有索引,但是我找到了一个脚本来执行此操作,但是我想获得6个特定的表,以免重建索引。

如何使用以下脚本完成此操作。在SQL中,我可以添加一个where条件,如:where table not in('table1','table2')。

USE sparcsn4prod

DECLARE @TableName varchar(255)

DECLARE TableCursor CURSOR FOR
SELECT table_name FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='base table'


OPEN TableCursor 


FETCH NEXT FROM TableCursor INTO @Tablename
WHILE @@FETCH_STATUS=0

BEGIN

DBCC DBREINDEX(@TableName,' ',90)

FETCH NEXT FROM TableCursor INTO @Tablename

END

CLOSE TableCursor

DEALLOCATE TableCursor

2 个答案:

答案 0 :(得分:2)

除了我认为游标是SQL Server Universe中最糟糕的发明之一(至少根据处理和性能)之外,您可以简单地扩展游标定义以过滤不需要的表名:

DECLARE TableCursor CURSOR FOR
SELECT table_name FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='base table'
  AND TABLE_NAME NOT IN ('table1','table2','table3')
OPEN TableCursor 

答案 1 :(得分:1)

Rather than re-invent the wheel, I suggest you consider using Ola Hallengren's Maintenance Solution. This allows one to exclude specific databases, tables, or indexes from normal index maintenance.

The dbo.IndexOptimize parameter value below will optimize all indexes except for the specified table.

@Indexes = N'ALL_INDEXES, -YourDB.YourSchema.YourTable'