是否可以显示视图中真正使用的列

问题描述 投票:0回答:1

考虑这样的视图:

CREATE TABLE t_test
(
    a int, 
    b int, 
    c int, 
    d int, 
    e int
)

CREATE VIEW v_test AS 
(
    WITH w_test AS  
    (
        SELECT *, c + d AS cd_computed 
        FROM t_test
    )
    SELECT a AS a_renamed, c, cd_computed 
    FROM w_test
)

如果我这样做(1)

SELECT * 
FROM information_schema.view_column_usage 
WHERE view_name = 'v_test'

我会得到

a,b,c,d,e

如果我这样做(2)

SELECT c.name 
FROM sys.columns c
INNER JOIN sys.views v ON c.object_id = v.object_id
WHERE v.name = 'v_test'

我会得到

a_renamed,c,cd_computed

但是我只想获取“规划者”真正使用的原始列来完成这项工作,因此,只有:

a,c,d
其他列
b and e
实际上在这些视图中毫无用处,不应该被使用“计划者”。

我认为/希望规划器可以在执行AS之前重写视图

WITH w_test AS 
(
    SELECT a, c, c + d AS cd_computed -- rewrite of this SELECT with only the usefull columns
    FROM t_test
)
SELECT a AS a_renamed, c, cd_computed 
FROM w_test

有什么方法可以检索这些信息吗?

sql-server view
1个回答
1
投票

您可以使用

sys.dm_sql_referenced_entities
系统功能来实现此目的。

select
  r.referenced_server_name,
  r.referenced_database_name,
  r.referenced_schema_name,
  r.referenced_entity_name,
  r.referenced_minor_name
from sys.dm_sql_referenced_entities ('dbo.v_test', 'OBJECT') r
where r.referenced_minor_name is not null;

db<>小提琴

请注意,

sys.sql_expression_dependencies
在您的情况下不起作用,因为不幸的是您没有在表引用中指定架构名称(本身就是一种不好的做法)。

© www.soinside.com 2019 - 2024. All rights reserved.