1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| DECLARE @TableName sysname,
@TABLE_SCHEMA sysname,
@IndexName sysname,
@FRAGMENTATION FLOAT,
@HEAP bit,
@SQL NVARCHAR(MAX);
DECLARE IndexCursor CURSOR
LOCAL FORWARD_ONLY STATIC READ_ONLY
FOR SELECT QUOTENAME(o.name) AS TableName,
QUOTENAME(s.name) AS TableSchema,
QUOTENAME(i.name) AS IndexName,
IPS.avg_fragmentation_in_percent,
CASE WHEN i.type_desc = 'HEAP' THEN 1 ELSE 0 END AS IS_HEAP
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'LIMITED') AS IPS
JOIN sys.indexes AS i ON IPS.object_id = i.object_id AND IPS.index_id = i.index_id
JOIN sys.objects AS o ON IPS.object_id = o.object_id
JOIN sys.schemas AS s ON o.schema_id = s.schema_id
WHERE avg_fragmentation_in_percent > 10
AND page_count > 64
ORDER BY avg_fragmentation_in_percent DESC;
OPEN IndexCursor;
FETCH NEXT FROM IndexCursor
INTO @TableName, @TABLE_SCHEMA, @IndexName, @FRAGMENTATION, @HEAP;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQL = CASE
WHEN @HEAP = 1
THEN N'ALTER TABLE ' + @TABLE_SCHEMA + N'.' + @TableName + ' REBUILD;'
WHEN @FRAGMENTATION > 30
THEN N' REBUILD;'
ELSE N'ALTER INDEX ' + @IndexName
+ N' ON ' + @TABLE_SCHEMA + N'.' + @TableName + N' REORGANIZE;'
END;
PRINT @SQL;
EXEC (@SQL);
FETCH NEXT FROM IndexCursor
INTO @TableName, @TABLE_SCHEMA, @IndexName, @FRAGMENTATION, @HEAP;
END
CLOSE IndexCursor;
DEALLOCATE IndexCursor; |
Partager