HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMinor

How to find all views with invalid column names

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
howallwithcolumnnamesviewsfindinvalid

Problem

I am trying to refresh all my views using code I found on the web:

DECLARE @ViewName VARCHAR(256)
DECLARE cViews CURSOR READ_ONLY FOR SELECT name from sys.views
OPEN cViews
FETCH NEXT FROM cViews INTO @ViewName
WHILE @@FETCH_STATUS != -1
BEGIN
    EXEC SP_REFRESHVIEW @ViewName
    PRINT 'View ''' + @ViewName + ''' has been refreshed.'
    FETCH NEXT FROM cViews INTO @ViewName
END
CLOSE cViews
DEALLOCATE cViews


I am getting the error Error Message: Invalid column name 'CloseDate'., but it's not telling me which view has the error. How would I find the name of all views with an invalid column name with the name of the invalid column? Thank you.

Solution

You could try importing the database into an SSDT database project and building the project. It should report this type of thing.

Alternatively you could try

SELECT *
FROM   sys.views
       CROSS APPLY sys.dm_sql_referenced_entities (
                                        CONCAT(QUOTENAME(SCHEMA_NAME(SCHEMA_ID)), '.', QUOTENAME(NAME)), 
                                        'OBJECT')


And then peruse the error output

Code Snippets

SELECT *
FROM   sys.views
       CROSS APPLY sys.dm_sql_referenced_entities (
                                        CONCAT(QUOTENAME(SCHEMA_NAME(SCHEMA_ID)), '.', QUOTENAME(NAME)), 
                                        'OBJECT')

Context

StackExchange Database Administrators Q#143348, answer score: 4

Revisions (0)

No revisions yet.