sql在一个范围内递归

时间:2016-01-13 22:54:32

标签: tsql recursive-query

我有一个SQL查询来形成一个树状视图的父/子结构,结果是这样的:

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

1 个答案:

答案 0 :(得分:2)

  • 我们在这里所做的只是为CTE中联合的第一部分添加lvl 0
  • 然后每次递归发生时(在all all之后)将其递增1
  • 然后在select中添加where子句以消除超过2的级别。

虽然我觉得这很奇怪但是因为你的代码中没有别名...

;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