How do I create a stored procedure that calls sp_refreshview for each view in the database?

你说的曾经没有我的故事 提交于 2020-01-02 14:29:24

问题


Today I run this

select 'exec sp_refreshview N''['+table_schema+'].['+table_name+']'''
from information_schema.tables
where table_type = 'view'

This generates a lot of: exec sp_refreshview N'[SCHEMA].[TABLE]'. I then copy the result to the query editor window and run all those execs.

How do I do this all at once? I would like to have a stored procedure called something like dev.RefreshAllViews which I can execute to do this...


回答1:


DECLARE @RefreshScript varchar(max)
set @RefreshScript = ''


select @RefreshScript= @RefreshScript + 'exec sp_refreshview N''['+table_schema+'].['+table_name+']''
'
from information_schema.tables
where table_type = 'view'



exec (@RefreshScript)

If there is ever any danger of your views having the [] characters in their names you might want to look at the QUOTENAME function.

Or Also with a cursor

DECLARE @viewName AS VARCHAR(255)

    DECLARE listOfViews CURSOR
        FOR SELECT  '[' + SCHEMA_NAME(uid) + '].[' + name + ']'
            FROM    sysobjects
            WHERE   xtype = 'V'


    OPEN listOfViews

    FETCH NEXT FROM listOfViews INTO @viewName

    WHILE ( @@FETCH_STATUS <> -1 )
        BEGIN


            FETCH NEXT FROM listOfViews INTO @viewName

            BEGIN TRY
                EXEC sp_refreshview @viewName
                PRINT @viewName + ' refreshed OK'
            END TRY
            BEGIN CATCH
                PRINT @viewName + ' refresh failed'
            END CATCH
        END

    CLOSE listOfViews

    DEALLOCATE listOfViews



回答2:


Check the system procedure SP_ExecuteSQL, which accepts a string and executes it.

You could write a stored procedure that opens a cursor on the query above, generates the proper strings, and executes them.




回答3:


DECLARE @Sql VARCHAR(MAX) = ''

SELECT @Sql += 'EXEC sys.sp_refreshview @viewname = N''' + QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) + '''' + CHAR(10) 
FROM INFORMATION_SCHEMA.VIEWS

PRINT @Sql
EXEC(@Sql)


来源:https://stackoverflow.com/questions/2491298/how-do-i-create-a-stored-procedure-that-calls-sp-refreshview-for-each-view-in-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!