我有一个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
答案 0 :(得分: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