/*******************************************************/
/* 功能:SQL Server 2005索引碎片整理 */
/* 邏輯碎片>=30重建索引,<30重新組織索引 */
/* 作者:賈桂軍 */
/* 日期:2008年6月11日 */
/*******************************************************/
/***********SQL Server 2005索引碎片整理*****************/
/**使用方法:將需要整理索引碎片的數據庫設置為當前數據庫**/
set nocount on
--使用游標重新組織指定庫中的索引,消除索引碎片
--R_T層游標取出當前數據庫所有表
declare R_T cursor
for select name from sys.tables
declare @T varchar(50)
open r_t
fetch next from r_t into @t
while @@fetch_status=0
begin
--R_index游標判斷指定表索引碎片情況並優化
declare R_Index cursor
for select t.name,i.name,s.avg_fragmentation_in_percent from sys.tables t
join sys.indexes i on i.object_id=t.object_id
join sys.dm_db_index_physical_stats(db_id(),object_id(@T),null,null,'limited') s
on s.object_id=i.object_id and s.index_id=i.index_id
declare @TName varchar(50),@IName varchar(50),@avg int,@str varchar(500)
open r_index
fetch next from r_index into @TName,@Iname,@avg
while @@fetch_status=0
begin
if @avg>=30 --如果碎片大於30,重建索引
begin
set @str='alter index '+rtrim(@Iname)+' on dbo.'+rtrim(@tname)+' rebuild'
end
else --如果碎片小於30,重新組織索引
begin
set @STR='alter index '+rtrim(@Iname)+' on dbo.'+rtrim(@tname)+' reorganize'
end
print @str
exec (@str) --執行
fetch next from r_index into @TName,@Iname,@avg
end
--結束r_index游標
close r_index
deallocate r_index
fetch next from r_t into @t
end
--結束R_T游標
close r_t
deallocate r_t
set nocount off
/*
--查看指定表的索引情況
select t.name,i.name,s.avg_fragmentation_in_percent from sys.tables t
join sys.indexes i on i.object_id=t.object_id
join sys.dm_db_index_physical_stats(db_id(),object_id('t2'),null,null,'limited') s
on s.object_id=i.object_id and s.index_id=i.index_id