您的位置:首页 > 数据库 > SQL

sqlserver索引维护(重新组织生成索引)

2016-03-31 14:26 736 查看
  sqlserver索引的维护

1:查看索引碎片大于百分三十以上的索引

select object_id= object_id,indexid = index_id,partitionnum = partition_number,frag= avg_fragmentation_in_percent
into #work_to_do
from sys.dm_db_index_physical_stats(db_id(), null, null , null, 'LIMITED') --dm_ph_stats join sys.dm_db_partition_stats dm_pa_st on dm_ph_stats.object_id=dm_pa_st.object_id
where avg_fragmentation_in_percent >= 30.0
and index_id > 0
and object_id in (select distinct a.object_id from sys.dm_db_partition_stats a join sys.indexes b
on a.object_id=b.object_id and a.index_id=b.index_id
where a.index_id>0
and a.in_row_data_page_count>1280 )

select a.object_id,a.name,a.type_desc,b.partitionnum ,b.frag,b.indexid from sys.indexes a , #work_to_do b
where a.object_id=b.object_id and a.index_id=b.indexid-- where object_id in(select objectid from #work_to_do)
--drop table #work_to_do


2:查看单表的索引碎片

SELECT a.index_id, name, avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats (DB_ID(N'MIAOSHUA'), OBJECT_ID(N'miaoshua.用户_注册信息表'), NULL, NULL, NULL) AS a
JOIN sys.indexes AS b ON a.object_id = b.object_id AND a.index_id = b.index_id;


看一下官网的推荐:

avg_fragmentation_in_percent

修复语句

> 5% 且 < = 30%

ALTER INDEX REORGANIZE

> 30%

ALTER INDEX REBUILD WITH (ONLINE = ON)*

所以说大于百分三十的索引是要重建的.

---------------------------------------------重新组织索引----------------------------------------

ALTER INDEX IX_Employee_OrganizationalLevel_OrganizationalNode ON HumanResources.Employee
REORGANIZE ;
GO


--------------------------------------------重新组织表中所有的索引--------------------------------------------

ALTER INDEX ALL ON HumanResources.Employee
REORGANIZE


-------------------------------------------重新生成的索引--------------------------------------------

ALTER INDEX PK_Employee_BusinessEntityID ON HumanResources.Employee
REBUILD;
GO


---------------------------------------------重新生成表中所有的索引--------------------------------------------

ALTER INDEX ALL ON Production.Product
REBUILD WITH (FILLFACTOR = 80, SORT_IN_TEMPDB = ON,
STATISTICS_NORECOMPUTE = ON);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: