2

I have a large number of SQL 2008 R2 views. I would like to know which database fields are referenced in the views. Is there a way that I can query the schema to list out these column names?

3 Answers 3

5

Use this query against sys.sql_dependencies.

SELECT
    ViewName = O.name,
    ReferencedTableName = X.name,
    ReferencedColumnName = C.name,

    T.is_selected,
    T.is_updated,
    T.is_select_all,

    ColumnType = M.name,
    M.max_length,
    M.precision,
    M.scale
FROM
    sys.sql_dependencies AS T
    INNER JOIN sys.objects AS O ON T.object_id = O.object_id
    INNER JOIN sys.objects AS X ON T.referenced_major_id = X.object_id
    INNER JOIN sys.columns AS C ON 
        C.object_id = X.object_id AND
        C.column_id = T.referenced_minor_id
    INNER JOIN sys.types AS M ON 
        M.system_type_id = C.system_type_id AND
        M.user_type_id = C.user_type_id
WHERE
    O.type = 'V'
ORDER BY
    O.name,
    X.name,
    C.name
1
  • Cool stuff, I did not know about sql_dependencies. +1 May 15, 2018 at 8:15
2

You can look at the view definition and see the referenced tables there. For that you can simply use sp_helptext like so:

sp_helptext 'vStores'

0

You can retrieve the view defintion from the metatdata in 'sys.objects', see also this answer:

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

That won't give you the underlying tables directly, though.

SQL Server does this trick itself when you define an object as having Schema Binding: when any objects are changed that are referenced by other objects using schema binding, that change is stopped and an error is given. Perhaps you can look into how SQL Server keeps track of those references to see what columns are used in a view. More on Schema binding here: https://www.mssqltips.com/sqlservertip/4673/benefits-of-schemabinding-in-sql-server/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.