当前位置: 代码网 > it编程>数据库>MsSqlserver > SQL2005重新生成索引的的存储过程 sp_rebuild_index

SQL2005重新生成索引的的存储过程 sp_rebuild_index

2024年06月02日 MsSqlserver 我要评论
公司运营着的网站,流量很大,网站是交互式的,经常在过了三四个月的时候索引生成的碎片就很多,由于很大一部分页面没有生成静态,这就导致网站在打开的速度上会变慢。以前都是手工右击索引重新生成,但是索引太多,

公司运营着的网站,流量很大,网站是交互式的,经常在过了三四个月的时候索引生成的碎片就很多,由于很大一部分页面没有生成静态,这就导致网站在打开的速度上会变慢。

以前都是手工右击索引重新生成,但是索引太多,操作起来费时费力,索引在网上找了个存储过程,自己整理了一下,执行的时候只需要选择相应的数据库,运行exec sp_rebuild_index即可,如下。

use [master]
go
set ansi_nulls on
go
set quoted_identifier on
go
create proc [dbo].[sp_rebuild_index] 
(
  @rebuild_fragmentation_percent smallint = 5  -- 当逻辑碎片百分比 > 5% 重新生成索引
)
as
begin
  /* 调用方法:
  1.针对当前实例所有数据库:  exec sys.sp_msforeachdb 'use ?;exec sp_rebuild_index'
  2.针对当前数据库:      exec sp_rebuild_index
  */
  
  --对系统数据库不作重新组织索引和重新生成索引
  if (db_name() in ('master','model','msdb','tempdb')) return;  
  
  --如果逻辑碎片(索引中的无序页)的百分比 <= 5% ,就不作重新组织索引和重新生成索引
  if not exists(select 1 from sys.dm_db_index_physical_stats(db_id(),null,null,null,null) a where a.index_id>0 and a.avg_fragmentation_in_percent > @rebuild_fragmentation_percent) return
  
  
  print replicate('-',60)+char(13)+char(10)+replicate(' ',14)+n'对数据库 '+quotename(db_name())+n' 进行索引优化'+replicate(' ',20)+char(13)+char(10)  
    
  declare @sql nvarchar(2000),@str nvarchar(2000)
  
  declare cur_x cursor for 
    select 'alter index '+quotename(a.name)+' on '+quotename(object_schema_name(a.object_id))+'.'+quotename(object_name(a.object_id))+' rebuild;' as [sql]
        ,n'重新生成索引:' +quotename(object_schema_name(a.object_id))+'.'+quotename(object_name(a.object_id))+'.'+quotename(a.name) as [str]
      from sys.indexes a
        inner join sys.dm_db_index_physical_stats(db_id(),null,null,null,null) b on b.object_id=a.object_id
          and b.index_id=a.index_id  
      where a.index_id>0  
        and b.avg_fragmentation_in_percent > @rebuild_fragmentation_percent
      order by object_name(a.object_id),a.index_id
      
  open cur_x
  fetch next from cur_x into @sql,@str  
  
  while (@@fetch_status = 0)
  begin
 print @sql
    exec(@sql)
 
    print @str
    fetch next from cur_x into @sql,@str  
      
  end
  close cur_x
  deallocate cur_x 
    
end


你可能在执行过程中会遇到如下错误

消息 195,级别 15,状态 10,过程 sp_rebuild_index,第 24 行
'object_schema_name' 不是可以识别的 内置函数名称。

不要担心,那是由于没有安装sql server sp4补丁造成的,安装一下补丁即可。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com