【问题标题】:structure this data so it can be read by a recursive cte? (SQL Server)构造这些数据以便递归 cte 可以读取它? (SQL 服务器)
【发布时间】:2016-05-21 01:22:24
【问题描述】:

我需要一个查询来返回给定以下信息的表的祖先。源表当前的结构如前所述,递归 CTE 不起作用。我似乎不知道应该如何构建源表以使 CTE 工作。

有人可以建议一个将返回以下内容的源表结构和查询吗?如果有比递归更好的方法,那也可以。

源表包含来自我的 SQL Server 数据库的反映数据沿袭的信息。为了生成表 T4,您需要执行过程 P1、P2 和 P3。

有一条规则,一个表只能有一个“父”过程,但一个过程可以构建多个表。所以 P3 可以构建 T3 和 T4,但 T3 只能由一个过程(P3)构建。

示例:

如果查询是“T4”,它应该返回以下信息:

referencing_ancestor    referenced_ancestors    
P3                      T2, LOOKUP_TABLE
P2                      T1
P1                      staging

这是当前结构中的源信息,但结构可以更改。我只需要给定表的祖先信息。

declare @Dependencies table
(
    id int identity(1,1),
    referencing_name nvarchar(50) NOT NULL,
    referenced_name nvarchar(50) NULL,
    select_from int NULL,
    insert_to int NULL
) 

insert into @Dependencies
select 'P1', 'staging', 1, 0    --> P1 selects data from staging
union all
select 'P1', 'T1', 0, 1         --> P1 populates T1
union all
select 'P2', 'T1', 1, 0         --> P2 selects data from T1
union all
select 'P2', 'T2', 0, 1         --> P2 populates T2
union all
select 'P3', 'LOOKUP_TABLE', 1, 0  --> P3 selects data from LOOKUP_TABLE
union all
select 'P3', 'T2', 1, 0         --> P3 selects data from T2
union all
select 'P3', 'T3', 0, 1         --> P3 populates  T3
union all
select 'P3', 'T4', 0, 1         --> P3 populates T4 

此查询不起作用,不知道如何解决:

 ;with ancestors as 
    (
        select referencing_name, referenced_name, Level = 0
        from @Dependencies
        where referenced_name = 'T4'

        union all

        select d.referencing_name, d.referenced_name, Level + 1
        from @Dependencies d
        inner join ancestors a on a.referenced_name = d.referenced_name
        where insert_to = 0
    )

    select * from ancestors  

【问题讨论】:

    标签: sql-server recursion


    【解决方案1】:

    我认为您可能希望在 @Dependencies 表本身中建立某种“级别”列,但在此示例中,我只是按 DENSE_RANK 函数中的引用名称排序。

    ;WITH ancestors AS (
        SELECT *, DENSE_RANK() OVER (ORDER BY referencing_name) AS tbl_level
        FROM    @Dependencies
    )
    SELECT  a2.* 
    FROM    ancestors a1
    JOIN    ancestors a2 ON a2.tbl_level <= a1.tbl_level
    WHERE   a1.referenced_name = 'T4'
    AND     a2.insert_to = 0 
    ORDER BY tbl_level DESC
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-15
      相关资源
      最近更新 更多