Domanda

I have this query that should build the hierarchial pathway for the categories in relation

;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 

Now I wonder why its going infinite!

I have the two tables this way:

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

Idealy the SQL should build pathways:

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

but its going infinite and giving recursive error, any help regarding this?

È stato utile?

Soluzione

I just realized I was doing one mistake,

if you closely examine the following lines then there comes the error:

select
    relation.RelationID

The issue is that RelationID never changes (thanks HABO) so I had to tweak it a little and replaced relation.RelationID with relation.ID as it always has to be unique.

Problem solved!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top