Skip to content

Instantly share code, notes, and snippets.

@ArtemAvramenko
Last active April 5, 2019 15:52
Show Gist options
  • Save ArtemAvramenko/d126b924133eb3c726f77204b2d1cf1a to your computer and use it in GitHub Desktop.
Save ArtemAvramenko/d126b924133eb3c726f77204b2d1cf1a to your computer and use it in GitHub Desktop.
SQL Server - reorganize all indexes
DECLARE @Indexes table (TableName nvarchar(MAX), IndexName nvarchar(MAX), Value int)
INSERT INTO @Indexes
SELECT
QuoteName(s.name) + '.' + QuoteName(t.name) as TableName,
QuoteName(i.name) as IndexName,
avg_fragmentation_in_percent as Value
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS ips
INNER JOIN sys.tables t on t.object_id = ips.object_id
INNER JOIN sys.schemas s on t.schema_id = s.schema_id
INNER JOIN sys.indexes AS i ON i.object_id = ips.object_id
AND ips.index_id = i.index_id
WHERE ips.database_id = DB_ID() AND avg_fragmentation_in_percent > 5
-- for each...
DECLARE @TableName nvarchar(MAX)
DECLARE @IndexName nvarchar(MAX)
DECLARE @Value int
DECLARE @Sql nvarchar(MAX)
DECLARE ItemCursor CURSOR FOR SELECT * FROM @Indexes
OPEN ItemCursor
WHILE 1 = 1
BEGIN
FETCH NEXT FROM ItemCursor INTO @TableName, @IndexName, @Value
IF @@FETCH_STATUS <> 0 BREAK
-- ...@TableName, @IndexName, @Value
SET @SQL = 'ALTER INDEX ' + @IndexName + ' ON ' + @TableName + ' REORGANIZE'
PRINT @SQL + ' -- ' + CAST(@Value as nvarchar(MAX)) + '%'
EXEC(@SQL)
END
CLOSE ItemCursor
DEALLOCATE ItemCursor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment