码迷,mamicode.com
首页 > 数据库 > 详细

SQL SERVER 查询与整理索引碎片

时间:2018-10-13 18:16:22      阅读:642      评论:0      收藏:0      [点我收藏+]

标签:class   ike   碎片   exe   oca   use   server   desc   重建   

重建索引

 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 查询与整理索引碎片

标签:class   ike   碎片   exe   oca   use   server   desc   重建   

原文地址:https://www.cnblogs.com/lionetchen/p/9783515.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!