Reputation: 22682
I've built a tool that uses table foreign keys but I'd like to extend it to support views.
Upvotes: 0
Views: 138
Reputation: 280252
In SQL Server 2008 and above, assuming you are only interested in dependencies within the same database, you can use the following query to determine all of the tables, views, and functions referenced within each view:
;WITH x AS
(
SELECT
v = QUOTENAME(OBJECT_SCHEMA_NAME(d.referencing_id))
+ '.' + QUOTENAME(OBJECT_NAME(d.referencing_id)),
t = QUOTENAME(OBJECT_SCHEMA_NAME(d.referenced_id))
+ '.' + QUOTENAME(OBJECT_NAME(d.referenced_id)),
td = o2.type_desc
FROM sys.sql_expression_dependencies AS d
INNER JOIN sys.objects AS o1
ON d.referencing_id = o1.[object_id]
INNER JOIN sys.objects AS o2
ON d.referenced_id = o2.[object_id]
WHERE o1.type_desc = 'VIEW'
)
SELECT [View] = v, Referenced_Object = t, [Type] = td
FROM x
GROUP BY v, t, td
ORDER BY v, t;
Upvotes: 2