Thursday, May 28, 2009

Use sp_refreshview to refresh view

When a table schema is updated the view does not update on its own.

sp_refreshview updates metadata of the specified view

To update a specifiec view

EXECUTE sp_refreshview '[VIEWNAME]'

To update all views that are dependent on a specified 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('[OBJECTNAME]');