Skip to content

Commit 7b60736

Browse files
authored
Update automate_index_rebuild.sql
1 parent 47a0547 commit 7b60736

File tree

1 file changed

+20
-20
lines changed

1 file changed

+20
-20
lines changed
Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,24 @@
1-
DECLARE @TableName NVARCHAR(255), @IndexName NVARCHAR(255), @SQL NVARCHAR(MAX);
2-
DECLARE frag_cursor CURSOR FOR
1+
USE University;
2+
GO
33

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');
4+
DECLARE @TableName NVARCHAR(255);
5+
DECLARE @SQL NVARCHAR(MAX);
116

12-
OPEN frag_cursor;
13-
FETCH NEXT FROM frag_cursor INTO @TableName, @IndexName;
7+
DECLARE table_cursor CURSOR FOR
8+
SELECT QUOTENAME(SCHEMA_NAME(t.schema_id)) + '.' + QUOTENAME(t.name)
9+
FROM sys.tables t
10+
WHERE t.is_ms_shipped = 0;
1411

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;
12+
OPEN table_cursor;
13+
FETCH NEXT FROM table_cursor INTO @TableName;
2214

23-
CLOSE frag_cursor;
24-
DEALLOCATE frag_cursor;
15+
WHILE @@FETCH_STATUS = 0
16+
BEGIN
17+
SET @SQL = 'ALTER INDEX ALL ON ' + @TableName + ' REBUILD WITH (FILLFACTOR = 90, SORT_IN_TEMPDB = ON);';
18+
PRINT 'Rebuilding indexes on: ' + @TableName;
19+
EXEC sp_executesql @SQL;
20+
FETCH NEXT FROM table_cursor INTO @TableName;
21+
END;
22+
23+
CLOSE table_cursor;
24+
DEALLOCATE table_cursor;

0 commit comments

Comments
 (0)