重建+重组索引的过程

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值