以递归方式查找与视图相关的所有表 sql server

Eri*_*ric 5 sql-server metadata

我有一个由其他视图(View-B View-C)组成的视图A,我想列出View-A使用的所有表(其中包括View-B和View-C中使用的表)。当我使用此代码时...

-- Get base tables for 'View-A' in Database-A 
USE Database-A 
GO
SELECT view_name, Table_Name
FROM INFORMATION_SCHEMA.VIEW_TABLE_USAGE
WHERE View_Name = 'View-A'
ORDER BY view_name, table_name
GO
Run Code Online (Sandbox Code Playgroud)

...我只得到了 View-A 立即使用的表以及其他视图的名称(View-B、View-C)。有没有办法递归获取 View-B 和 View-C 也使用的表的名称?

Mat*_*att 1

此查询为您提供两列:父列和子列,显示级联关系(例如,view a依赖于、依赖于等):view bview btable c

with deps (parent, child) as (
    select vtu.view_name, table_name
    from information_schema.view_table_usage as vtu
    where view_name = 'YOUR_VIEW_NAME'
    union all
    select vtu.view_name, vtu.table_name
    from information_schema.view_table_usage as vtu
    inner join deps on deps.child = vtu.view_name
)
select parent, child
from deps;
Run Code Online (Sandbox Code Playgroud)

如果您不担心父子之间的关系,可以将选择更改为

select distinct child
from deps;
Run Code Online (Sandbox Code Playgroud)

  • 请停止使用“information_schema”视图。值得一读 @aaronbertrand - [反对 INFORMATION_SCHEMA 视图的案例](https://sqlblog.org/2011/11/03/the-case-against-information_schema-views) (3认同)