Assuming this table
ParentId ChildId SortOrder
---------------------------------
0 1 0
1 2 1
2 3 1
2 4 2
2 6 3
1 7 2
1 9 3
9 10 1
9 12 2
how would i write a simple CTE (or another type of query) that would return them parent/child relationships at any level but keeping the sort-order for all child-items below the parent.
basically, this would be a simple tree-view with sub-items ordered by a specific sort-order.
sql server 2008 is the db
update:
there can be infinite parent/child levels – i tried some examples from other stack question/answers but none included a sortorder at the child level.
an example result should be:
parent (sort 0)
child (sort 1)
child (sort 2)
child (sort 3)
child-child (sort 1)
child (sort 4)
child-child (sort 1)
child-child (sort 2)
etc.
hope this makes sense – maybe i’m looking at this wrong and this sort of result is better to be constructed within the mid-tier?
anyway, any feedback is greatly appreciated
Recursive CTE with special sort override. Note the sort override in the children of 2 (I modified the source table slightly to test this ability)
Result: