博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

浅谈mssql2000的sp_recompile和sp_refreshview

Posted on 2005-10-20 20:57  单摆  阅读(909)  评论(1编辑  收藏  举报

浅谈mssql2000的sp_recompile和sp_refreshview
1、sp_recompile
说明:使存储过程和触发器在下次运行时重新编译
原因:存储过程和触发器所用的查询只在编译时进行优化。对数据库进行了索引或其它会影响数据库统计的更改后,已编译的存储过程和触发器可能会失去效率。通过对作用于表上的存储过程和触发器进行重新编译,可以重新优查询。
方法:执行下面的脚本就可以将数据库的所有存储过程在下次运行时重新编译
declare @objName varchar(250)
declare #_cursor cursor for

select name  from sysobjects where type='TR' OR type='P'  order by type
open #_cursor

fetch next from #_cursor into @objName
while @@fetch_status=0
 begin   
  exec sp_recompile @objName  
  fetch next from #_cursor into @objName
 end
close #_cursor
deallocate #_cursor
print '完成'

2、sp_refreshview
说明:刷新指定视图的元数据。由于视图所依赖的基础对象的更改,视图的持久元数据会过期
原因:修改完表,相应的视图没有发生变化是很痛苦的事情,或许这个是微软的bug,希望mssql2005不会出现这个问题,^_^
方法:执行下面的脚本就可以将数据库的所有视图的元数据

declare @ViewName varchar(250)
declare @i int
set @i=0
declare #_cursor cursor for

select name  from sysobjects where type='V'

open #_cursor

fetch next from #_cursor into @viewname

while @@fetch_status=0
 begin
  print '成功刷新视图: '+ @viewname 
  exec sp_refreshview @viewname  
  set @i= @i +1 
  fetch next from #_cursor into @viewname
 end

close #_cursor
deallocate #_cursor
print '完成'
print '共成功刷新' + convert(varchar(10),@i) + '个视图'