重建+重组索引的过程

use master
go
alter Procedure P_ReIndex
as
begin
declare @s varchar(8000)=
'

set nocount on ;
create table #t( t varchar(8000))
insert #t(t)
SELECT /* a.index_id 编号,        b.NAME 名称,c.sch,c.tbl,
        CONVERT(NVARCHAR(20), avg_fragmentation_in_percent) + ''%'' 碎片百分比,
        avg_fragmentation_in_percent,*/
        (
        case when avg_fragmentation_in_percent>30
        then ''
        use [?]
        begin try
        ALTER INDEX [''+b.NAME+''] ON [''+c.sch+''].[''+c.tbl+''] REBUILD WITH (ONLINE = ON)
        print ''''索引重新生成:?   [''+c.sch+''].[''+c.tbl+'']:[''+b.NAME+'']成功!''''
        end try
        begin catch
        print ''''索引重新生成:?   [''+c.sch+''].[''+c.tbl+'']:[''+b.NAME+'']失败!''''
        print ''''失败代码:''''+error_message()
        end catch
        ''
        else ''
        use [?]
        begin try
        ALTER INDEX [''+b.NAME+''] ON [''+c.sch+''].[''+c.tbl+''] REORGANIZE
        print ''''索引重新组织:?   [''+c.sch+''].[''+c.tbl+'']:[''+b.NAME+'']成功!''''
        end try
        begin catch
        print ''''索引重新组织:?   [''+c.sch+''].[''+c.tbl+'']:[''+b.NAME+'']失败!''''
        print ''''失败代码:''''+error_message()
        end catch
        ''
        end
        )
FROM    [?].sys.dm_db_index_physical_stats(db_id(''?''),
                                       NULL, NULL,
                                       NULL, NULL) AS a
        JOIN [?].sys.indexes AS b ON a.object_id = b.object_id
                                 AND a.index_id = b.index_id
join (select b.name sch,a.name tbl,a.object_id  from [?].sys.all_objects a inner join [?].sys.schemas b
on a.schema_id=b.schema_id and a.type=''u''
) c on a.object_id=c.object_id
WHERE   NAME IS NOT NULL
        AND avg_fragmentation_in_percent > 5
ORDER BY avg_fragmentation_in_percent DESC
declare @s varchar(8000)
declare cu_guanli_index cursor for
select t from #t
open cu_guanli_index
fetch next from cu_guanli_index into @s
while @@FETCH_STATUS=0
begin
exec(@s)
fetch next from cu_guanli_index into @s
end
close cu_guanli_index
deallocate cu_guanli_index
drop table #t
'
exec sp_MSforeachdb @s
end

 

你可能感兴趣的:(重建+重组索引的过程)