Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine table referenced in a view in SQL Server

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?

Hope this clears the question. Let me know if not.

Please guide! Thanks!

like image 382
xorpower Avatar asked Nov 29 '11 09:11

xorpower


People also ask

How do you find the underlying table of a view?

You find the details in dictionary tablesSELECT * FROM dba_viewsWHERE view_name = <view name >TEXT column contains the actual query which used while creating views and this will give details what are all tables used.

How do I find the referenced table in SQL?

SELECT name as Foreign_Key ,schema_name(schema_id) as Schema_Name ,object_name(parent_object_id) as Table_Name FROM sys. foreign_keys WHERE Referenced_object_id = object_id('dbo. user','U'); if your table belongs to a different schema other than dbo then replace the schema name.

How do I find the source of a view in SQL Server?

In Object Explorer, expand the database that contains the view to which you want to view the properties, and then expand the Views folder. Right-click the view of which you want to view the properties and select View Dependencies. Select Objects that depend on [view name] to display the objects that refer to the view.

How can you tell if a table is referenced?

You can use the OBJECTPROPERTY() function in SQL Server to check whether or not a table is referenced by a foreign key. To do this, pass the table's object ID as the first argument, and TableHasForeignRef as the second argument.


2 Answers

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) .

like image 185
GSerg Avatar answered Nov 06 '22 10:11

GSerg


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
like image 40
DigCamara Avatar answered Nov 06 '22 10:11

DigCamara