SQL Server Rebuild Index

來源:互聯網
上載者:User

標籤:des   io   ar   os   使用   sp   for   on   log   

USE [msdb]
GO

/****** Object:  StoredProcedure [dbo].[IndexMaintain]    Script Date: 6/14/2013 1:46:17 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE  procedure  [dbo].[IndexMaintain] 
as  
SET NOCOUNT on
 
BEGIN TRY
 declare @EXCEPTION VARCHAR(MAX)
 declare @MailSubject NVARCHAR(255)
 declare @DBName NVARCHAR(255)
 declare @TableName NVARCHAR(255)
 declare @SchemaName NVARCHAR(255)
 declare @IndexName NVARCHAR(255)
 declare @avg_fragmentation_in_percent_old DECIMAL(18,3)
 declare @avg_page_space_used_in_percent_old DECIMAL(18,3)
 declare @avg_fragmentation_in_percent_new DECIMAL(18,3)
 declare @avg_page_space_used_in_percent_new DECIMAL(18,3)
        
 declare @Defrag NVARCHAR(max)
 declare @Sql NVARCHAR(max)
 declare @ParmDefinition nvarchar(500)
 set @EXCEPTION=‘‘
 
 --刪除#Frag
 if exists(select *  from sys.objects where object_id=object_id(N‘#Frag‘))
 drop table #Frag
   
 --定義暫存資料表#Frag儲存index Fragment   
 create table #Frag(
     DBname  NVARCHAR(255),
     TableName NVARCHAR(255),
     SchemaName NVARCHAR(255),
     IndexName NVARCHAR(255),
     AvgFragment DECIMAL(18,3),
     avg_page_space_used DECIMAL(18,3)
     )

 --去除DataBass為READ_ONLY
 declare dbstatus cursor for
  select name
  from sys.databases
  where DatabasePropertyEx(name,‘Updateability‘)<>‘READ_ONLY‘AND state_desc=‘ONLINE‘
 open dbstatus
 fetch next from dbstatus into @DBName
 while @@FETCH_STATUS=0
 begin
  set @sql=‘insert into #Frag(DBname, TableName,SchemaName,IndexName,AvgFragment,avg_page_space_used)
   select ‘‘[‘[email protected]+‘]‘‘ AS DBName,‘‘[‘‘+t.Name+‘‘]‘‘ AS TableName, sc.Name AS SchemaName, ‘‘[‘‘+i.name+‘‘]‘‘ AS IndexName, s.avg_fragmentation_in_percent, s.avg_page_space_used_in_percent 
   from ‘[email protected]+‘.sys.dm_db_index_physical_stats(DB_ID(‘‘‘[email protected]+‘‘‘),NULL,NULL,NULL,‘‘Sampled‘‘) AS s
   join ‘[email protected]+‘.sys.indexes i on s.Object_Id=i.Object_id and s.Index_id=i.Index_id
   join ‘[email protected]+‘.sys.tables t on i.Object_id=t.Object_ID
   join ‘[email protected]+‘.sys.schemas sc on t.schema_id=sc.SCHEMA_ID
   where s.avg_fragmentation_in_percent  >20 and t.type=‘‘U‘‘ and s.page_count>8 and i.allow_page_locks=1 and i.allow_row_locks=1
   order by  TableName,IndexName‘
  exec(@sql)
  fetch next from dbstatus into @DBName
 end
 close dbstatus
 deallocate dbstatus

 --定義CURSOR遍曆暫存資料表#Frag,根據Fragment大小採取不同的方案維護index.
 declare cList CURSOR for
   select *  from  #Frag
 open cList
 fetch next from cList into @DBName,@TableName,@SchemaName,@IndexName,@avg_fragmentation_in_percent_old,@avg_page_space_used_in_percent_old
 while @@FETCH_STATUS=0
 begin
    --Fragment between 20.0 and 40.0 ,使用 Alter INDEX reorganize整理片段
    if @avg_fragmentation_in_percent_old between 20.0 and 40.0 
    begin      
   --整理片段
   set @Defrag=N‘Alter INDEX   ‘+‘‘[email protected]+‘ on ‘[email protected]+‘.‘[email protected]+‘.‘[email protected]+‘ reorganize‘
   exec sp_executesql @Defrag
        
   --擷取index被整理後的片段比例
   set @Sql=N‘USE ‘[email protected]+‘; select @avg_fragmentation_in_percent_new_temp=s.avg_fragmentation_in_percent,@avg_page_space_used_in_percent_new_temp= s.avg_page_space_used_in_percent
     from  ‘[email protected]+‘.sys.indexes i 
     inner join ‘[email protected]+‘.sys.dm_db_index_physical_stats(db_id(replace(replace(‘‘‘[email protected]+‘‘‘,‘‘[‘‘,‘‘‘‘),‘‘]‘‘,‘‘‘‘)), object_id(‘‘‘[email protected]+‘‘‘‘+‘),null,null,‘‘sampled‘‘) as s on   i.index_id=s.index_id 
     where i.object_id=object_id(‘‘‘[email protected]+‘‘‘‘+‘)and i.name=‘‘‘[email protected]+‘‘‘‘
   set @ParmDefinition=N‘@avg_fragmentation_in_percent_new_temp  DECIMAL(18,3) output,@avg_page_space_used_in_percent_new_temp DECIMAL(18,3) output‘
   exec sp_executesql @Sql,@ParmDefinition ,@[email protected]_fragmentation_in_percent_new output, @[email protected]_page_space_used_in_percent_new output
     
   --write log
   insert [dbo].IndexDefrag values(@DBName,@TableName,@SchemaName,@IndexName,getdate(),@avg_fragmentation_in_percent_old,@avg_page_space_used_in_percent_old,@avg_fragmentation_in_percent_new,@avg_page_space_used_in_percent_new,‘0‘)
    end
  --Fragment大於40.0 ,使用 Alter INDEX rebuild整理片段
    else if @avg_fragmentation_in_percent_old >40.0
    begin      
   --整理片段
   set @Defrag=N‘Alter INDEX    ‘+‘‘[email protected]+‘ on ‘[email protected]+‘.‘[email protected]+‘.‘[email protected]+‘ rebuild‘
   exec sp_executesql @Defrag
     
   --擷取index被整理後的片段比例
   set @Sql=N‘USE ‘[email protected]+‘;select @avg_fragmentation_in_percent_new_temp=s.avg_fragmentation_in_percent,@avg_page_space_used_in_percent_new_temp= s.avg_page_space_used_in_percent
     from  ‘[email protected]+‘.sys.indexes i 
     inner join ‘[email protected]+‘.sys.dm_db_index_physical_stats(db_id(replace(replace(‘‘‘[email protected]+‘‘‘,‘‘[‘‘,‘‘‘‘),‘‘]‘‘,‘‘‘‘)), object_id(‘‘‘[email protected]+‘‘‘‘+‘),null,null,‘‘sampled‘‘) as s on   i.index_id=s.index_id 
     where i.object_id=object_id(‘‘‘[email protected]+‘‘‘‘+‘)and i.name=‘‘‘[email protected]+‘‘‘‘
   set @ParmDefinition=N‘@avg_fragmentation_in_percent_new_temp  DECIMAL(18,3) output,@avg_page_space_used_in_percent_new_temp DECIMAL(18,3) output‘
   exec sp_executesql @Sql,@ParmDefinition ,@[email protected]_fragmentation_in_percent_new output, @[email protected]_page_space_used_in_percent_new output
     
   --write log
   insert [dbo].IndexDefrag values(@DBName,@TableName,@SchemaName,@IndexName,getdate(),@avg_fragmentation_in_percent_old,@avg_page_space_used_in_percent_old,@avg_fragmentation_in_percent_new,@avg_page_space_used_in_percent_new,‘1‘)
  end
   fetch next from cList into @DBName,@TableName,@SchemaName,@IndexName,@avg_fragmentation_in_percent_old,@avg_page_space_used_in_percent_old
 end
 close cList
 deallocate cList
END TRY
BEGIN CATCH
 SET @EXCEPTION = ERROR_MESSAGE()
END CATCH

IF @EXCEPTION<>‘‘
BEGIN
 SET @MailSubject=‘[Important] SDS DB Index Maintainence failed from ‘ + @@SERVERNAME 
 EXEC msdb.dbo.sp_send_dbmail
 @profile_name = ‘SDSCSQL‘,                    
 @recipients = ‘[email protected]‘,
 [email protected]_recipients =‘[email protected];[email protected]‘,
 [email protected]_copy_recipients =‘‘,
 @body = @EXCEPTION,
 @subject = @MailSubject
 
END
 
GO


 

SQL Server Rebuild Index

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.