sql - How to get all children of parent item when all are in the same row and table -


i have table of parts , sub-parts each record contains primary part record along childpart.

part - childpart    -    b    -    c    -    d c    -    f c    -    z f    -    r z    -    r q    -    b q    -    c 

so example above, part a has 7 total descendants (b, c, d, f, z, r, r). parent part can have multiple children , child part can belong more 1 parent; notice part b used both a , q.

how can efficiently show child parts of given parent part using joins , not using sql cursors or loops? hierarchical tree theoretically infinitely deep.

you can use recursive cte:

declare @pid varchar(20) = 'a'  ;with cte (    select childpart    mytable    part = @pid     union     select t1.childpart    mytable t1    inner join cte t2 on t1.part = t2.childpart ) select childpart cte 

Comments

Popular posts from this blog

java - pagination of xlsx file to XSSFworkbook using apache POI -

Unlimited choices in BASH case statement -

apache - How do I stop my index.php being run twice for every user -