Skip to content

Commit 5bbc9fb

Browse files
authored
Create automate_index_rebuild.sql
1 parent 5366e87 commit 5bbc9fb

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
DECLARE @TableName NVARCHAR(255), @IndexName NVARCHAR(255), @SQL NVARCHAR(MAX);
2+
DECLARE frag_cursor CURSOR FOR
3+
4+
SELECT QUOTENAME(SCHEMA_NAME(t.schema_id)) + '.' + QUOTENAME(t.name),
5+
QUOTENAME(i.name)
6+
FROM
7+
sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'LIMITED') AS ps
8+
INNER JOIN sys.indexes i ON ps.object_id = i.object_id AND ps.index_id = i.index_id
9+
INNER JOIN sys.tables t ON i.object_id = t.object_id
10+
WHERE ps.avg_fragmentation_in_percent > 30 AND i.type_desc IN ('CLUSTERED', 'NONCLUSTERED');
11+
12+
OPEN frag_cursor;
13+
FETCH NEXT FROM frag_cursor INTO @TableName, @IndexName;
14+
15+
WHILE @@FETCH_STATUS = 0
16+
BEGIN
17+
SET @SQL = 'ALTER INDEX ' + @IndexName + ' ON ' + @TableName + ' REBUILD;';
18+
PRINT 'Rebuilding index: ' + @IndexName + ' on ' + @TableName;
19+
EXEC sp_executesql @SQL;
20+
FETCH NEXT FROM frag_cursor INTO @TableName, @IndexName;
21+
END;
22+
23+
CLOSE frag_cursor;
24+
DEALLOCATE frag_cursor;

0 commit comments

Comments
 (0)