我有这个查询应该为相关类别建立层次结构路径
;with cte as
(
select
CAST(1 as int) as RelationID,
1 CategoryID,
c.Name Name
,CAST(('') as varchar(1000)) as Indent,CAST(c.Name as varchar(1000)) as Pathway,0 as Level
from
Categories c
where
c.ID = 1
union all
select
relation.RelationID,
relation.CategoryID,
c.Name Name
,CAST(('|— ' + cte.Indent) as varchar(1000)) as Indent,CAST((cte.Pathway + '/' + c.Name) as varchar(1000)) as Pathway,cte.Level + 1 as Level
from
Category_Relations relation
inner join
Categories c on c.Id = relation.CategoryID
inner join cte on cte.RelationID = relation.RelationID
where c.ID > 1
)
select * from cte
现在我想知道为什么它会无限!
我这样有两张桌子:
Categories:
ID,Name
1,Main
2,Cat1
3,Cat2
4,Cat3
5,Cat4
6,Cat1.1
7,Cat1.2
8,Cat2.1
9,Cat3.1
Category_Relations:
ID,RelationID,CategoryID
1,0,1 (main cat)
2,1,2
3,1,3
4,1,4
5,1,5
6,2,6
7,2,7
8,3,8
9,4,9
理想情况下,SQL 应该构建路径:
main
main/cat1
main/cat2
main/cat3
main/cat4
main/cat1/cat1.1
main/cat1/cat1.2
main/cat2/cat2.1
main/cat3/cat3.1
但它会无限并给出递归错误,对此有什么帮助吗?