SQL SERVER 查詢與整理索引碎片
阿新 • • 發佈:2018-10-13
des locate begin declare unit percent pre arch lte
重建索引
1 use DATABASE_NAME; 2 3 DECLARE @TableName VARCHAR(255) 4 DECLARE @sql NVARCHAR(500) 5 DECLARE @fillfactor INT 6 SET @fillfactor = 80 7 DECLARE TableCursor CURSOR FOR 8 SELECT OBJECT_SCHEMA_NAME([object_id])+‘.[‘+name+‘]‘ AS TableName 9 FROM sys.tables w 10 OPEN TableCursor 11 FETCH NEXTFROM TableCursor INTO @TableName 12 WHILE @@FETCH_STATUS = 0 13 BEGIN 14 SET @sql = ‘ALTER INDEX ALL ON ‘ + @TableName + ‘ REBUILD WITH (ONLINE=off,FILLFACTOR=80);‘ --‘ REBUILD WITH (FILLFACTOR = ‘ + CONVERT(VARCHAR(3),@fillfactor) + ‘)‘ 15 exec (@sql) 16 FETCH NEXT FROM TableCursor INTO @TableName 17END 18 CLOSE TableCursor 19 DEALLOCATE TableCursor 20 GO
查詢索引碎片
use DATABASE_NAME; SELECT dbschemas.[name] as ‘Schema‘, dbtables.[name] as ‘Table‘, dbindexes.[name] as ‘Index‘, indexstats.alloc_unit_type_desc, indexstats.avg_fragmentation_in_percent, indexstats.page_count FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS indexstats INNER JOIN sys.tables dbtables on dbtables.[object_id] = indexstats.[object_id] INNER JOIN sys.schemas dbschemas on dbtables.[schema_id] = dbschemas.[schema_id] INNER JOIN sys.indexes AS dbindexes ON dbindexes.[object_id] = indexstats.[object_id] AND indexstats.index_id = dbindexes.index_id WHERE indexstats.database_id = DB_ID() and dbindexes.[name] not like ‘pk_%‘ ORDER BY indexstats.avg_fragmentation_in_percent * page_count desc
SQL SERVER 查詢與整理索引碎片