考虑这样的视图:
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
有什么方法可以检索这些信息吗?
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;
请注意,
sys.sql_expression_dependencies
在您的情况下不起作用,因为不幸的是您没有在表引用中指定架构名称(本身就是一种不好的做法)。