关于重新组织和重新生成索引sp_RefreshIndex的介绍
网络编程 2021-07-05 13:42www.168986.cn编程入门
本篇文章长沙网络推广为大家介绍,关于重新组织和重新生成索引sp_RefreshIndex的介绍。需要的朋友参考下
开始:
--------------------------------------------------------------------------------
在上周,客户反映一个系统问题,当处理大量数据的时候,出现网络超时。后来,我们跟踪测试,发现是由于索引碎片多而引起的网络超时。
解决方法,自然是重新组织和重新生成索引。在这里,我写了一个存储过程sp_RefreshIndex来实现。
存储过程sp_RefreshIndex:
代码如下:
use master
go
if object_id('sp_RefreshIndex') Is not null
Drop Proc sp_RefreshIndex
Go
create proc sp_RefreshIndex
(
@Reanize_Fragmentation_Percent smallint = 5 -- 当逻辑碎片百分比 > 5% 重新组织索引
,@Rebuild_Fragmentation_Percent smallint = 30 -- 当逻辑碎片百分比 > 30% 重新生成索引
)
as
begin
/* 调用方法:
.针对当前实例所有数据库: exec sys.sp_MSforeachdb 'use ?;exec sp_RefreshIndex'
.针对当前数据库: exec sp_RefreshIndex
*/
--对系统数据库不作重新组织索引和重新生成索引
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 > @Reanize_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))+case when b.avg_fragmentation_in_percent<=@Rebuild_Fragmentation_Percent then ' reanize;'else ' rebuild;'end as [sql]
,case when b.avg_fragmentation_in_percent<=@Rebuild_Fragmentation_Percent then N'重新组织索引:' else N'重新生成索引:'end +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 > @Reanize_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
exec(@sql)
print @str
fetch next from cur_x into @sql,@str
end
close cur_x
deallocate cur_x
end
go
exec sp_ms_marksystemobject 'sp_RefreshIndex'
go
调用方法:
代码如下:
use master
go
exec sys.sp_MSforeachdb 'use ?;exec sp_RefreshIndex'
go
注:我们根据实际的环境,修改@Reanize_Fragmentation_Percent 和 @Rebuild_Fragmentation_Percent 值。
存储过程 sp_RefreshIndex 已在狼蚁网站SEO优化的环境测试通过:
SQL Server 2005 (SP4)/2008/2008R2/2012
扩展:
--------------------------------------------------------------------------------
我们可以把上面的SQL代码写入Job。再通过SQL Agent 服务,选择一个月或两个月执行一次job。
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程