gpt4 book ai didi

sql - 如何获取 View 中的列级依赖关系

转载 作者:行者123 更新时间:2023-12-02 00:53:19 24 4
gpt4 key购买 nike

我已经对这个问题做了一些研究,但还没有解决方案。我想要得到的是 View 中的列级依赖关系。所以,假设我们有一个这样的表

create table TEST(
first_name varchar(10),
last_name varchar(10),
street varchar(10),
number int
)

和这样的 View :

create view vTEST
as
select
first_name + ' ' + last_name as [name],
street + ' ' + cast(number as varchar(max)) as [address]
from dbo.TEST

我想要得到这样的结果:

column_name depends_on_column_name depends_on_table_name
----------- --------------------- --------------------
name first_name dbo.TEST
name last_name dbo.TEST
address street dbo.TEST
address number dbo.TEST

我已经尝试过sys.dm_sql_referenced_entities函数,但对于 View ,referencing_minor_id 始终为 0。

select
referencing_minor_id,
referenced_schema_name + '.' + referenced_entity_name as depends_on_table_name,
referenced_minor_name as depends_on_column_name
from sys.dm_sql_referenced_entities('dbo.vTEST', 'OBJECT')

referencing_minor_id depends_on_table_name depends_on_column_name
-------------------- --------------------- ----------------------
0 dbo.TEST NULL
0 dbo.TEST first_name
0 dbo.TEST last_name
0 dbo.TEST street
0 dbo.TEST number

sys.sql_expression_dependencies 也是如此。和过时的 sys.sql_dependencies .

那么我错过了什么或者是不可能做到的吗?

有一些相关的问题( Find the real column name of an alias used in a view? ),但正如我所说 - 我还没有找到可行的解决方案。

编辑1:我尝试使用DAC来查询此信息是否存储在System Base Tables中的某个位置但没找到

最佳答案

此解决方案只能部分回答您的问题。它不适用于表达式列。

您可以使用sys.dm_exec_describe_first_result_set获取列信息:

@include_browse_information

If set to 1, each query is analyzed as if it has a FOR BROWSE option on the query. Additional key columns and source table information are returned.

CREATE TABLE txu(id INT, first_name VARCHAR(10), last_name VARCHAR(10));
CREATE TABLE txd(id INT, id_fk INT, address VARCHAR(100));

CREATE VIEW v_txu
AS
SELECT t.id AS PK_id,
t.first_name AS name,
d.address,
t.first_name + t.last_name AS name_full
FROM txu t
JOIN txd d
ON t.id = d.id_fk

主要查询:

SELECT name, source_database, source_schema,
source_table, source_column
FROM sys.dm_exec_describe_first_result_set(N'SELECT * FROM v_txu', null, 1) ;

输出:

+-----------+--------------------+---------------+--------------+---------------+
| name | source_database | source_schema | source_table | source_column |
+-----------+--------------------+---------------+--------------+---------------+
| PK_id | fiddle_0f9d47226c4 | dbo | txu | id |
| name | fiddle_0f9d47226c4 | dbo | txu | first_name |
| address | fiddle_0f9d47226c4 | dbo | txd | address |
| name_full | null | null | null | null |
+-----------+--------------------+---------------+--------------+---------------+

<强> DBFiddleDemo

关于sql - 如何获取 View 中的列级依赖关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45658957/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com