[zhuan]自动整理索引碎片的代码

--------------------------------------------------------------------------------
--
 ensure a use databse statement has been executed first.
--
------------------------------------------------------------------------------
 
USE GB_BEJ--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 '数据库ID:' + CONVERT(VARCHAR(10),@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_idNULLNULLNULL'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
        
        
        
PRINT 'Executed: ' + @command    
        
        
EXEC (@command)
        

        
FETCH NEXT FROM partitions INTO @objectid@indexid@partitionnum,
            
@frag
    
END

-- free resource
CLOSE partitions
DEALLOCATE partitions
DROP TABLE #work_to_do
原文地址:https://www.cnblogs.com/itelite/p/2091893.html