SQLSERVER索引碎片整理脚本
2010-11-11 16:29
232 查看
-------------------------------------------------------------------------------- -- ensure a use databse statement has been executed first. -------------------------------------------------------------------------------- use DBName set nocount on declare @objectid int ,@indexid int ,@partitioncount bigint ,@schemaname sysname ,@objectname sysname ,@indexname sysname ,@partitionnum bigint ,@partitions bigint ,@frag float ,@command varchar(1000) ,@db_id int set @db_id = db_id() print @db_id select objectid = 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') where avg_fragmentation_in_percent > 5.0 and index_id > 0 -- declare the cursor for the list of partitions to be processed. declare partitions cursor for select * from #work_to_do -- Open the cursor. open partitions -- Loop through the partitions. fetch next from partitions into @objectid, @indexid, @partitionnum, @frag while @@fetch_status = 0 begin select @objectname = o.name, @schemaname = s.name from sys.objects as o inner join sys.schemas as s on s.schema_id = o.schema_id where o.object_id = @objectid select @indexname = name from sys.indexes where object_id = @objectid and index_id = @indexid select @partitioncount = count (*) from sys.partitions where object_id = @objectid and index_id = @indexid -- 30 is an arbitrary decision point at which to switch between reorganizing and rebuilding if @frag < 30.0 begin select @command = 'alter index [' + @indexname + '] on ' + @schemaname + '.' + @objectname + ' reorganize' if @partitioncount > 1 select @command = @command + ' partition=' + convert(char, @partitionnum) end if @frag >= 30.0 begin select @command = 'alter index [' + @indexname +'] on ' + @schemaname + '.' + @objectname + ' rebuild' if @partitioncount > 1 select @command = @command + ' partition=' + convert(char, @partitionnum) end exec (@command) print 'Executed: ' + @command fetch next from partitions into @objectid, @indexid, @partitionnum, @frag end -- free resource close partitions deallocate partitions drop table #work_to_do
相关文章推荐
- SQL Server 2005:索引碎片整理脚本
- SQL索引碎片整理脚本
- DBA日常维护:SqlServer 索引碎片整理
- SQL Server 2005:索引碎片整理脚本
- SQL Server 2005:索引碎片整理脚本
- Sqlserver:在sql2005查看索引的碎片统计情况,并给出处理意见的自动化批处理脚本
- SQL Server 2005:索引碎片整理脚本(网摘)
- 微软MSDN提供的索引碎片整理脚本
- 在线整理索引碎片脚本
- 索引碎片情况,表行数,批整理脚本
- MSSQL中整理索引碎片的存储过程
- 整理索引及表碎片
- 通过DBCC整理Sqlserver数据库表索引碎片
- 使用 DBCC SHOWCONTIG 和 DBCC DBREINDEX 对数据库中的索引进行碎片整理
- 【整理】SqlServer在视图上创建索引的条件
- SQLServer中的索引碎片处理
- 检测和整理索引碎片
- MSSQL数据库表索引碎片整理优化性能
- 提升SQL Server速度 整理索引碎片
- SqlServer索引碎片