Refresh all views in a database

Updates the metadata for the specified non-schema-bound view. Persistent metadata for a view can become outdated because of changes to the underlying objects upon which the view depends.

This scripts help to refresh all view in selected database.

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
	BEGIN TRY
	    EXECUTE sp_refreshview @ActualView;
	END TRY
	BEGIN CATCH
		PRINT 'View '+@ActualView+' cannot be refreshed.';
	END CATCH;
	FETCH NEXT FROM viewlist
	INTO @ActualView;	
END;
CLOSE viewlist;
DEALLOCATE viewlist;
EXECUTE sp_refreshview N'Sales.vIndividualCustomer';

Updates all views that have dependencies on a changed object

SELECT DISTINCT 'EXEC sp_refreshview ''' + name + ''''
FROM sys.objects AS so
INNER JOIN sys.sql_expression_dependencies AS sed ON so.object_id = sed.referencing_id
WHERE so.type = 'V'
	AND sed.referenced_id = OBJECT_ID('Person.Person');

https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-refreshview-transact-sql?view=sql-server-ver15

Spread the love

Leave a Comment