【问题标题】:Index Defragmentation in SQL Server 2012SQL Server 2012 中的索引碎片整理
【发布时间】:2025-12-31 19:55:01
【问题描述】:

我正在运行来自 SQLFOOL 和 SQL Authorities 等的不同脚本,但是当我检查数据库时,我根本看不到任何碎片整理。我写了一些代码,但不能正常工作,你能帮帮我吗?

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 附近的语法不正确

【问题讨论】:

  • 您不需要Alter index all on @table_name 的动态 SQL 吗?它是 SQL 2012 的新功能吗?
  • 我真的不知道如何在 SQL 中编写动态任务。我将尝试对此进行研究
  • 为什么不安排一个维护工作来重建所有索引,比如说,每周?没有以这种方式编写/调试/维护的查询。
  • 感谢萨尔曼,我试过了,对我有用。

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


【解决方案1】:

您肯定需要考虑一个有效的解决方案,然后编写您自己的查询。更好的解决方案是使用这个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

【讨论】:

    最近更新 更多