rebuild_index.sql 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. begin
  2. declare @databaseName sysname = N'SN7_SERVER_SCHEMA';
  3. declare @rebuildFloor float = 40;
  4. declare @schemaName sysname;
  5. declare @tableName sysname;
  6. declare @indexName sysname;
  7. declare @fragmentation float;
  8. declare @command nvarchar(500);
  9. print N'Rebuild index started at: ' + convert( nvarchar(100), SYSDATETIME(), 20 );
  10. print N'-------------------------------------------------------------------------';
  11. -- select indexes for rebuild
  12. declare indexCursor cursor fast_forward local for
  13. select s.name schema_name, t.name table_name, i.name index_name, d.avg_fragmentation_in_percent fragmentation
  14. from sys.dm_db_index_physical_stats( DB_ID(@databaseName), null, null, null, null) d
  15. inner join sys.tables t on d.object_id = t.object_id
  16. inner join sys.schemas s on t.schema_id = s.schema_id
  17. inner join sys.indexes i on d.object_id = i.object_id AND d.index_id = i.index_id
  18. where d.index_id > 0
  19. and d.avg_fragmentation_in_percent > 10
  20. and d.page_count > 8
  21. open indexCursor;
  22. while( 1=1 )
  23. begin
  24. fetch next from indexCursor into @schemaName, @tableName, @indexName, @fragmentation;
  25. if @@FETCH_STATUS <> 0 break;
  26. begin try
  27. set @command = N'ALTER INDEX ' + @indexName + N' ON ' + @databaseName + N'.' + @schemaName + N'.' + @tableName;
  28. if @fragmentation < @rebuildFloor
  29. begin
  30. set @command = @command + N' REORGANIZE;';
  31. set @command = @command + N' UPDATE STATISTICS ' + @databaseName + N'.' + @schemaName + N'.' + @tableName + N' ' + @indexName + N';';
  32. end
  33. else
  34. begin
  35. set @command = @command + N' REBUILD WITH (ONLINE = ON); ';
  36. end;
  37. --print @command;
  38. exec (@command);
  39. print N'INDEX ' + @indexName + N'ON ' + @databaseName + N'.' + @schemaName + N'.' + @tableName + N' SUCCESSFULLY PROCESSED';
  40. end try
  41. begin catch
  42. print N'ERROR REBUILD INDEX ' + @indexName;
  43. print N'ERROR MESSAGE: ' + ERROR_MESSAGE();
  44. end catch
  45. end;
  46. print N'-------------------------------------------------------------------------';
  47. print N'Rebuild index completed at: ' + convert( nvarchar(100), SYSDATETIME(), 20 );
  48. close indexCursor;
  49. deallocate indexCursor;
  50. end;