views:

95

answers:

3

Is there a way that i can find out what base tables are being used by views using a custom query or stored procedure?

+1  A: 

Here's a good explanation:
http://blogs.techrepublic.com.com/datacenter/?p=277

JeremySpouken
i get no results when i create and run that sp
rs
+1  A: 

You could use the sql_dependencies view:

select OBJECT_NAME(referenced_major_id) as DependantObject
from sys.sql_dependencies
where object_id = object_id('YourViewName')

To recursively retrieve dependencies (f.e., if you select from a view, this would find the tables that the other view references):

with deps (child, parent) as (
    select d.object_id, d.referenced_major_id
    from sys.sql_dependencies d
    where d.object_id = object_id('YourViewName')
    union all
    select d.object_id, d.referenced_major_id
    from sys.sql_dependencies d
    inner join deps on deps.parent = d.object_id
)
select OBJECT_NAME(parent)
from deps

This method is not fool-proof. For example, if you rename an object using sp_rename, its dependencies are not updated.

Andomar
i get no results when i run this
rs
Works fine on my machine. Maybe you could post the definition of the view?
Andomar
yes it works for only views which i created but for other views created by other developers (to which i have access) i get 0 records.
rs
If the views created by other developers are in another schema, try to qualify the view name like `where d.object_id = object_id('OtherDevSchema.OtherDevView')`
Andomar
no they are in same schema
rs
Just double checking, are you aware of the difference between a schema and a database? The syntax is `database.schema.object`, for example `MyDb.MySchema.MyView`
Andomar
+1  A: 

If this is something you'll be doing often Red Gate SQL Dependency Tracker (no I don't work for them) is a great tool. I think they have a trial period if you want to try it.

Christopherous 5000