如何在SQL Server中刷新数据库中的所有视图

huwehgph  于 2022-12-03  发布在  SQL Server
关注(0)|答案(2)|浏览(224)

我想刷新数据库中的所有视图,因为我重命名了表中的一些列并添加了更多列,所以我需要通过刷新来更新所有视图
我只将所有视图创建为select * from tableName

r6vfmomb

r6vfmomb1#

谢谢你们的回复,但下面的问题满足了我的要求

SET NOCOUNT ON

DECLARE @ActualView varchar(255)

DECLARE viewlist CURSOR FAST_FORWARD
FOR
SELECT
    DISTINCT s.name + '.' + o.name AS ViewName
FROM sys.objects o JOIN sys.schemas s ON o.schema_id = s.schema_id 
WHERE   o.[type] = 'V'
        AND OBJECTPROPERTY(o.[object_id], 'IsSchemaBound') <> 1
        AND OBJECTPROPERTY(o.[object_id], 'IsMsShipped') <> 1

OPEN viewlist

FETCH NEXT FROM viewlist 
INTO @ActualView

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT @ActualView
    EXEC sp_refreshview @ActualView

    FETCH NEXT FROM viewlist
    INTO @ActualView
END
CLOSE viewlist
DEALLOCATE viewlist
6yt4nkrj

6yt4nkrj2#

您可以使用此方法,

DECLARE @sqlcmd NVARCHAR(MAX) = ''
SELECT @sqlcmd = @sqlcmd +  'EXEC sp_refreshview ''' + name + ''';
' 
FROM sys.objects AS so 
WHERE so.type = 'V' 

--SELECT @sqlcmd     //**uncomment this line if you want to see all views names

EXEC(@sqlcmd)

相关问题