Skip to content

Commit 47a0547

Browse files
authored
Update rebuild_all_index_in_db.sql
1 parent 5bbc9fb commit 47a0547

File tree

1 file changed

+28
-19
lines changed

1 file changed

+28
-19
lines changed
Lines changed: 28 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,33 @@
1-
USE University;
2-
GO
1+
USE University;
2+
GO
33

4-
DECLARE @TableName NVARCHAR(255);
5-
DECLARE @SQL NVARCHAR(MAX);
4+
DECLARE @TableName NVARCHAR(255);
5+
DECLARE @IndexName NVARCHAR(255);
6+
DECLARE @SQL NVARCHAR(MAX);
67

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;
8+
DECLARE frag_cursor CURSOR FOR
9+
SELECT
10+
QUOTENAME(SCHEMA_NAME(t.schema_id)) + '.' + QUOTENAME(t.name),
11+
QUOTENAME(i.name)
12+
FROM
13+
sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'LIMITED') AS ps
14+
JOIN sys.indexes i ON ps.object_id = i.object_id AND ps.index_id = i.index_id
15+
JOIN sys.tables t ON i.object_id = t.object_id
16+
WHERE
17+
ps.avg_fragmentation_in_percent > 30
18+
AND i.type_desc IN ('CLUSTERED', 'NONCLUSTERED');
1119

12-
OPEN table_cursor;
13-
FETCH NEXT FROM table_cursor INTO @TableName;
20+
OPEN frag_cursor;
21+
FETCH NEXT FROM frag_cursor INTO @TableName, @IndexName;
1422

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;
23+
WHILE @@FETCH_STATUS = 0
24+
BEGIN
25+
SET @SQL = 'ALTER INDEX ' + @IndexName + ' ON ' + @TableName + ' REBUILD WITH (FILLFACTOR = 90, SORT_IN_TEMPDB = ON);';
26+
PRINT 'Rebuilding index: ' + @IndexName + ' on table: ' + @TableName;
27+
EXEC sp_executesql @SQL;
2228

23-
CLOSE table_cursor;
24-
DEALLOCATE table_cursor;
29+
FETCH NEXT FROM frag_cursor INTO @TableName, @IndexName;
30+
END;
31+
32+
CLOSE frag_cursor;
33+
DEALLOCATE frag_cursor;

0 commit comments

Comments
 (0)