DECLARE @tableNames varchar(500)
SET @tableNames='xxx,DB2, ' -- 关键此处填写需要刷新视图的数据库名称
DECLARE @i_start int
SET @i_start=1;
DECLARE @i_end int
SET @i_end = CHARINDEX(',', @tableNames, @i_start);
DECLARE @tableName varchar(30)
declare @s nvarchar(1000) -- 注意此处改为nvarchar(1000)
WHILE @i_end>0
BEGIN
SET @tableName= LTrim(RTrim(SUBSTRING(@tableNames, @i_start, @i_end-@i_start)))
--select @tableName
if exists(select * from master..sysdata s where name=@tableName)
begin
print '更新 数据库['+ @tableName+']所有视图'
if exists (select * from tempdb.dbo.sys s where id = _id(N'tempdb..#tempTable') and type='U')
begin
drop table #tempTable
end
create table #tempTable (_sql_ nvarchar(1000))
SET @s = 'USE '+@tableName+' select ''USE '+@tableName+ ' EXECUTE sp_refreshview '' + name from sys s where [xtype]=''V'''
insert into #tempTable(_sql_)
exec sp_executesql @s
---游标循环遍历--
declare @temp nvarchar(1000)
--声明游标
declare order_cursor cursor
for(select * from #tempTable)
--打开游标--
open order_cursor
--开始循环游标变量--
fetch next from order_cursor into @temp
while @@FETCH_STATUS = 0 --返回被 FETCH语句执行的最后游标的状态--
begin
--print @temp
exec (@temp) --OK
--exec sp_executesql @temp --OK
fetch next from order_cursor into @temp --转到下一个游标,没有会死循环
end
close order_cursor --关闭游标
deallocate order_cursor --释放游标
--用完之后要把临时表清空
drop table #tempTable--需要注意的是,这种方法不能嵌套。
end
SET @i_start = @i_end + 1;
SET @i_end = CHARINDEX(',', @tableNames, @i_start);
END
继续阅读与本文标签相同的文章
-
四川省内江市与阿里巴巴签署数字经济建设战略合作
2026-05-18栏目: 教程
-
2019云栖大会 | 超干货!这一场,一起玩转分布式数据库云上最佳实践
2026-05-18栏目: 教程
-
降低 80% 的读写响应延迟!我们测评了 etcd 3.4 新特性(内含读写发展史)
2026-05-18栏目: 教程
-
渗透测试对网站安全扫描与检测流程
2026-05-18栏目: 教程
-
云上容器服务基础镜像制作
2026-05-18栏目: 教程
