如何查看SQL Server的索引碎片情况并进行整理

一、查看碎片占用情况

SELECT OBJECT_NAME(ind.OBJECT_ID) AS TableName, 
ind.name AS IndexName, indexstats.index_type_desc AS IndexType, 
indexstats.avg_fragmentation_in_percent 
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) indexstats 
INNER JOIN sys.indexes ind  
ON ind.object_id = indexstats.object_id 
AND ind.index_id = indexstats.index_id 
WHERE indexstats.avg_fragmentation_in_percent > 30 
ORDER BY indexstats.avg_fragmentation_in_percent DESC

说明:为了获得最佳性能,avg_fragmentation_in_percent的值应尽可能接近零。

 

 

二、sql server中index的REBUILD和REORGANIZE

  

--1.准备实验数据
select * into Employee from AdventureWorks2008R2.HumanResources.Employee;

--2.查看使用空间:Employee    290            72 KB    56 KB    8 KB    8 KB
sp_spaceused Employee

--3.创建聚集索引
create clustered index IX_BusinessEntityID on Employee(BusinessEntityID);

--4.查看使用空间:Employee    290            80 KB    56 KB    16 KB    8 KB
sp_spaceused Employee

--5.索引重建,清除fragment,并设定fillfactor为60
ALTER INDEX ALL ON Employee
REBUILD WITH (FILLFACTOR = 60, SORT_IN_TEMPDB = ON,
              STATISTICS_NORECOMPUTE = ON);

--6.查看使用空间:Employee    290            144 KB    88 KB    16 KB    40 KB
sp_spaceused Employee

---不锁表,索引重建

ALTER INDEX ALL ON Tab_Dealer_InteractiveMessage
REORGANIZE
GO

 

 


---生成索引重建sql

SELECT distinct

 concat('ALTER INDEX ALL ON ', OBJECT_NAME(ind.OBJECT_ID),' REORGANIZE - GO-') AS ReIndex
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) indexstats
INNER JOIN sys.indexes ind  
ON ind.object_id = indexstats.object_id
AND ind.index_id = indexstats.index_id
WHERE indexstats.avg_fragmentation_in_percent > 30
   

---查询索引碎片sql
SELECT

 concat('ALTER INDEX ALL ON ', OBJECT_NAME(ind.OBJECT_ID),' REORGANIZE - GO-') AS ReIndex,

OBJECT_NAME(ind.OBJECT_ID) AS TableName,
ind.name AS IndexName, indexstats.index_type_desc AS IndexType,
indexstats.avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) indexstats
INNER JOIN sys.indexes ind  
ON ind.object_id = indexstats.object_id
AND ind.index_id = indexstats.index_id
WHERE indexstats.avg_fragmentation_in_percent > 30
 
ORDER BY indexstats.avg_fragmentation_in_percent DESC

 


--DBCC SHOWCONTIG('Tab_Dealer_ProductPrice');

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值