sp_refreshview
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.
Run the following SP to refresh all views in the database, after there was database object modifications.
CREATE PROCEDURE [dbo].[uspRefreshViews]
AS
BEGIN;
SET NOCOUNT ON;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
BEGIN
SET NOCOUNT ON
DECLARE @views TABLE
( id INT IDENTITY(1,1) not null,
schemaName NVARCHAR(128),
viewName NVARCHAR(128) not null
);
DECLARE
@maxID INT,
@id INT = 0,
@aViewName NVARCHAR (128) = '',
@aSchemaViewName NVARCHAR(258)
INSERT INTO @views
SELECT sch.name, vw.name
FROM sys.views vw
INNER JOIN sys.schemas sch ON sch.schema_id = vw.schema_id
SELECT @maxID = coalesce(@@ROWCOUNT,0)
WHILE @id <> @maxID
BEGIN
SELECT TOP 1 @id = id, @aSchemaViewName = schemaName + '.' + viewName
FROM @views
WHERE @id < id
ORDER BY id ASC
PRINT 'Refreshing ' + @aSchemaViewName
EXECUTE sp_refreshview @aSchemaViewName
END
END
Comments