SQL SERVER 查询与整理索引碎片

Posted 小狮儿

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL SERVER 查询与整理索引碎片相关的知识,希望对你有一定的参考价值。

重建索引

 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 NEXT FROM 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
17 END
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 查询与整理索引碎片的主要内容,如果未能解决你的问题,请参考以下文章

SQL Server索引碎片整理实际操作记录

SQL Server索引碎片整理实际操作记录

检查SQL Server 2005的索引密度和碎片信息(转)

SQL Server数据库表索引碎片整理

T-SQL查询高级—SQL Server索引中的碎片和填充因子

sql server 索引阐述系列五 索引参数与碎片