|
| 1 | +USE SUSDB; |
| 2 | +GO |
| 3 | +SET NOCOUNT ON; |
| 4 | + |
| 5 | +DECLARE @schema sysname, @table sysname, @index sysname, @sql nvarchar(max); |
| 6 | + |
| 7 | +DECLARE cur CURSOR FAST_FORWARD FOR |
| 8 | +SELECT |
| 9 | + s.name AS SchemaName, |
| 10 | + t.name AS TableName, |
| 11 | + i.name AS IndexName, |
| 12 | + ips.avg_fragmentation_in_percent AS Frag, |
| 13 | + ips.page_count AS Pages |
| 14 | +FROM sys.dm_db_index_physical_stats(DB_ID('SUSDB'), NULL, NULL, NULL, 'LIMITED') AS ips |
| 15 | +JOIN sys.indexes AS i ON ips.object_id = i.object_id AND ips.index_id = i.index_id |
| 16 | +JOIN sys.tables AS t ON t.object_id = i.object_id |
| 17 | +JOIN sys.schemas AS s ON s.schema_id = t.schema_id |
| 18 | +WHERE i.name IS NOT NULL |
| 19 | + AND ips.page_count >= 100 -- evita trabalho inútil |
| 20 | + AND i.is_disabled = 0 |
| 21 | + AND i.type_desc <> 'HEAP' -- heaps não têm REBUILD |
| 22 | +ORDER BY ips.avg_fragmentation_in_percent DESC; |
| 23 | + |
| 24 | +OPEN cur; |
| 25 | +DECLARE @frag float, @pages int; |
| 26 | + |
| 27 | +FETCH NEXT FROM cur INTO @schema, @table, @index, @frag, @pages; |
| 28 | +WHILE @@FETCH_STATUS = 0 |
| 29 | +BEGIN |
| 30 | + IF @frag >= 30 |
| 31 | + SET @sql = N'ALTER INDEX ['+@index+'] ON ['+@schema+'].['+@table+'] REBUILD WITH (SORT_IN_TEMPDB = OFF, MAXDOP = 1);'; |
| 32 | + ELSE IF @frag >= 5 |
| 33 | + SET @sql = N'ALTER INDEX ['+@index+'] ON ['+@schema+'].['+@table+'] REORGANIZE;'; |
| 34 | + ELSE |
| 35 | + SET @sql = NULL; -- ignora |
| 36 | + |
| 37 | + IF @sql IS NOT NULL |
| 38 | + BEGIN |
| 39 | + PRINT CONCAT('>> ', @schema, '.', @table, ' [', @index, '] Frag=', CONVERT(varchar(10), @frag), '% Pages=', @pages); |
| 40 | + EXEC sp_executesql @sql; |
| 41 | + END |
| 42 | + |
| 43 | + FETCH NEXT FROM cur INTO @schema, @table, @index, @frag, @pages; |
| 44 | +END |
| 45 | + |
| 46 | +CLOSE cur; DEALLOCATE cur; |
| 47 | +GO |
0 commit comments