sql 在一个范围内递归

sql recursive within a range

我有一个 sql 查询以形成树状视图的 parent/child 结构,结果是这样的:

lvl1a

lvl1a/lvl2a

lvl1a/lvl2b

lvl1b/lvl2a/lvl3a

lvl1c

lvl1d/lvl2a/lvl3a/lvl4a

...

查询本身没有限制范围,例如,如果我只想获得第一级和第二级的树状视图 有人可以修改 sql 查询来添加这样的功能吗? tks

;with cte as
     (
     select 
         labelID, 
         Title, 
         ParentLevel, 
         cast(Title as varchar(max)) as [treePath]
         from TestTable
         where ParentLevel = 0
         union all
             select
                 t.labelID,
                 t.Title,
                 t.ParentLevel,
                 [treePath] + '/' + cast(t.Title as varchar(255))
             from
                 cte
             join TestTablet on cte.labelID = t.ParentLevel
         )

     select  
         labelID,
         Title,
         ParentLevel,
         [treePath]
     from cte 
     order by treePath
  • 我们在这里所做的只是为 CTE 中联合的第一部分添加 0 级
  • 然后每次递归发生时将其递增 1(在 union all 之后)
  • 然后向 select 添加一个 where 子句以消除超过 2 的级别。

尽管我觉得这很奇怪,因为 t 在您的代码中没有别名... .

;with cte as
     (
     select 
         labelID, 
         Title, 
         ParentLevel, 
         cast(Title as varchar(max)) as [treePath],
         0 as lvl
         from TestTable
         where ParentLevel = 0
         union all
             select
                 t.labelID,
                 t.Title,
                 t.ParentLevel,
                 [treePath] + '/' + cast(t.Title as varchar(255)),
                 cte.lvl+1 as lvl
             from
                 cte
             join TestTablet t on cte.labelID = t.ParentLevel
         )

     select  
         labelID,
         Title,
         ParentLevel,
         [treePath]
     from cte 
     where lvl <=2
     order by treePath