Determine table referenced in a view in SQL Server

后端 未结 4 681
终归单人心
终归单人心 2020-12-29 14:08

How can i get to know the tables used in a view in SQL Server? Is there a script or a tool that could let me know the tables used in a view and can also list down the fields

相关标签:
4条回答
  • 2020-12-29 14:18

    This information is available from the INFORMATION_SCHEMA

    SELECT * 
        FROM    INFORMATION_SCHEMA.VIEW_COLUMN_USAGE AS cu
        JOIN    INFORMATION_SCHEMA.COLUMNS AS c
        ON      c.TABLE_SCHEMA  = cu.TABLE_SCHEMA
        AND     c.TABLE_CATALOG = cu.TABLE_CATALOG
        AND     c.TABLE_NAME    = cu.TABLE_NAME
        AND     c.COLUMN_NAME   = cu.COLUMN_NAME
        WHERE   cu.VIEW_NAME    = 'viewtablename';
    
    0 讨论(0)
  • 2020-12-29 14:27

    You can use DISTINCT to get only the tables.

      Select   DISTINCT cols.referenced_entity_name from  
       sys.sql_expression_dependencies objs   outer apply
       sys.dm_sql_referenced_entities (
       OBJECT_SCHEMA_NAME(objs.referencing_id) + N'.' +
       object_name(objs.referencing_id), N'OBJECT' ) as cols where  
       objs.referencing_id = object_id('viewname')
    
    0 讨论(0)
  • 2020-12-29 14:35
    select
      cols.*
    from
      sys.sql_expression_dependencies objs
      outer apply sys.dm_sql_referenced_entities ( OBJECT_SCHEMA_NAME(objs.referencing_id) + N'.' + object_name(objs.referencing_id), N'OBJECT' ) as cols
    where
      objs.referencing_id = object_id('view_name_here')
    

    Reference: sys.dm_sql_referenced_entities (Transact-SQL) .

    0 讨论(0)
  • 2020-12-29 14:36

    The simplest way to see the content of (most) objects would be:

    sp_helptext blah
    

    Where you substitute blah with the name of the object. This would yield the actual code which created the object. in this case, for instance it could result in:

    CREATE VIEW blah
    AS
      select blah.column1,blah.column2 from blah_table
    
    0 讨论(0)
提交回复
热议问题