Para verificar a fragmentação do banco de dados, e identificar se é preciso efetuar um Rebuild na base de dados, execute o script abaixo.
GO
SELECT a.index_id, name, avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats (DB_ID(N'AdventureWorks2012'),
OBJECT_ID(N'HumanResources.Employee'), NULL, NULL, NULL) AS a
JOIN sys.indexes AS b ON a.object_id = b.object_id AND a.index_id = b.index_id;
GO
SELECT
RowNum = ROW_NUMBER() OVER(ORDER BY t.TABLE_NAME)
,TableName = t.TABLE_SCHEMA + '.' + t.TABLE_NAME
,AlterMe = 'ALTER INDEX ALL ON [' + t.TABLE_SCHEMA + '].[' + t.TABLE_NAME + '] REBUILD;'
INTO #Reindex_Tables
FROM INFORMATION_SCHEMA.TABLES t
WHERE TABLE_TYPE = 'BASE TABLE'
DECLARE @Iter INT
DECLARE @MaxIndex INT
DECLARE @ExecMe VARCHAR(MAX)
SET @Iter = 1
SET @MaxIndex =
(
SELECT COUNT(1)
FROM #Reindex_Tables
)
WHILE @Iter <= @MaxIndex
BEGIN
SET @ExecMe =
(
SELECT AlterMe
FROM #Reindex_Tables
WHERE RowNum = @Iter
)
EXEC (@ExecMe)
PRINT @ExecMe + ' Executed'
SET @Iter = @Iter + 1
END
Verificando a fragmentação de uma base de dados
GO
SELECT a.index_id, name, avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats (DB_ID(N'AdventureWorks2012'),
OBJECT_ID(N'HumanResources.Employee'), NULL, NULL, NULL) AS a
JOIN sys.indexes AS b ON a.object_id = b.object_id AND a.index_id = b.index_id;
GO
Executando um rebuild em toda a base de dados:
SELECT
RowNum = ROW_NUMBER() OVER(ORDER BY t.TABLE_NAME)
,TableName = t.TABLE_SCHEMA + '.' + t.TABLE_NAME
,AlterMe = 'ALTER INDEX ALL ON [' + t.TABLE_SCHEMA + '].[' + t.TABLE_NAME + '] REBUILD;'
INTO #Reindex_Tables
FROM INFORMATION_SCHEMA.TABLES t
WHERE TABLE_TYPE = 'BASE TABLE'
DECLARE @Iter INT
DECLARE @MaxIndex INT
DECLARE @ExecMe VARCHAR(MAX)
SET @Iter = 1
SET @MaxIndex =
(
SELECT COUNT(1)
FROM #Reindex_Tables
)
WHILE @Iter <= @MaxIndex
BEGIN
SET @ExecMe =
(
SELECT AlterMe
FROM #Reindex_Tables
WHERE RowNum = @Iter
)
EXEC (@ExecMe)
PRINT @ExecMe + ' Executed'
SET @Iter = @Iter + 1
END
Comentários