DECLARE @tableName VARCHAR(50), @indexName VARCHAR(100), @frag FLOAT, @dSQL NVARCHAR(MAX)
DECLARE indexCursor CURSOR FOR
SELECT o.name, i.name, avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL,NULL,NULL) ps
INNER JOIN sys.objects o
ON ps.object_id = o.object_id
AND o.type = 'U'
INNER JOIN sys.indexes i
ON ps.object_id = i.object_id
AND ps.index_id = i.index_id
WHERE i.name IS NOT NULL --AND avg_fragmentation_in_percent > 7
OPEN indexCursor
FETCH NEXT FROM indexCursor INTO @tableName, @indexName, @frag
WHILE @@FETCH_STATUS <> -1
BEGIN
SET @dSQL = ''
IF @frag BETWEEN 5 AND 30
BEGIN
SET @dSQL = 'ALTER INDEX ' + @indexName + ' ON ' + @tableName + ' REORGANIZE'
END
IF @frag > 30
BEGIN
SET @dSQL = 'ALTER INDEX ' + @indexName + ' ON ' + @tableName + ' REBUILD'
END
IF @frag < 5
BEGIN
SET @dSQL = '-- INDEX ' + @indexName + ' ON ' + @tableName + ' did not need defragging'
END
EXEC sp_executeSQL @dSQL
PRINT @dSQL
FETCH NEXT FROM indexCursor INTO @tableName, @indexName, @frag
END
CLOSE indexCursor
DEALLOCATE indexCursor
Your proc is a bit of a mess and hard to read. This should get you what you need though. I added a little logic in the middle that determines if the index should be reorged, or rebuilt.
Thanks! I'll take a look at your code. Although I'm inclined to think my code was on the right track as it does work fine from SSMS....
No comments:
Post a Comment