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!
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!
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) .
referenced_entity_name
and column names are in referenced_minor_name
. If it doesn't for you, try providing a more qualified name of the view (such as dbo.view_name
) or recompiling the view before examining it. –
Carlisle select referenced_entity_name,referenced_minor_name from sys.dm_sql_referenced_entities ( 'dbo.foo', N'OBJECT' ) where referenced_minor_name is not null
? The OUTER APPLY
just seems to bring in additional rows as it is repeatedly called with the same values. –
Ornithology sp_refreshview
for all views. –
Carlisle outer apply
yields no data whereas a direct call does, then sys.sql_expression_dependencies
doesn't contain any rows for which outer apply
could have been called. That's an issue. –
Carlisle 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
Using below simple query you can know which tables are used in view:
SELECT view_name, Table_Name
FROM INFORMATION_SCHEMA.VIEW_TABLE_USAGE
WHERE View_Name = 'ViewName'
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';
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')
© 2022 - 2024 — McMap. All rights reserved.