SQL Server 2012中的索引碎片整理

时间:2015-10-29 00:39:49

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

我从SQLFOOL&运行不同的脚本SQL权限等等,但是当我检查数据库时,根本看不到任何碎片整理。我写了一些不起作用的代码,请你帮个忙吗?

Declare @table_name Varchar (70);

Declare table_cursor Cursor for 
     select OBJECT_SCHEMA_NAME([OBJECT_ID])+'.' + NAME AS Tablenamee 
     from sys.tables

open table_cursor
Fetch next from table_cursor into @table_name

While @@fetch_status = 0
begin
    Alter index all on @table_name
      REBUILD WITH (FILLFACTOR=80, ONLINE=ON) 

    fetch next from table_cursor into @table_name
end 

Close table_cursor
deallocate table_cursor

获取错误

  

@table_name附近的语法不正确

1 个答案:

答案 0 :(得分:0)

您肯定需要考虑一个有效的解决方案,然后编写自己的查询。更好的解决方案是使用此https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html

Declare @table_name as Varchar(70);
declare @sql as nvarchar(max);
DECLARE @ParmDefinition NVARCHAR(100);

Declare table_cursor Cursor for 
     select top 10 OBJECT_SCHEMA_NAME([OBJECT_ID])+'.' + NAME AS Tablenamee 
     from sys.tables

open table_cursor
Fetch next from table_cursor into @table_name

While @@fetch_status = 0
begin
    set @sql = N'Alter index all on ' + @table_name +'
      REBUILD WITH (FILLFACTOR=80, ONLINE=ON)';

      SET @ParmDefinition = N'@table_name varchar(70)';

      EXECUTE sp_executesql @sql, 
                              @ParmDefinition, 
                              @table_name = @table_name;

    fetch next from table_cursor into @table_name
end 

Close table_cursor
deallocate table_cursor