创建刷新视图的存储过程,入参是表名。用于修改表结构后批量更新所有视图。
例如在patient_mi表里新增了字段,如果视图不刷新可能会有串列的情况。
以下面的格式执行存储过程,刷新所有用到patient_mi这张表的视图:
exec RefreshOurView 'patient_mi'
存储过程脚本:
CREATE PROCEDURE RefreshOurView
@table_name varchar(200)
AS
BEGIN
DECLARE MyCursor CURSOR
FOR SELECT OBJECT_NAME(referencing_id) AS referencing_entity_name
FROM sys.sql_expression_dependencies AS sed
INNER JOIN sys.objects AS o ON sed.referencing_id = o.object_id
WHERE referenced_id = OBJECT_ID(N'' + @table_name + '') and o.type_desc = 'VIEW'
DECLARE @view_name varchar(40)
OPEN MyCursor
FETCH NEXT FROM MyCursor
INTO @view_name
WHILE (@@fetch_status <> -1)
BEGIN
IF (@@fetch_status <> -2)
begin
PRINT @view_name
EXEC sp_refreshview @view_name
END
FETCH NEXT FROM MyCursor INTO @view_name
END
CLOSE MyCursor
DEALLOCATE MyCursor
END
路过的点个赞再走,谢谢~