Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
Log in  ::  Register  ::  Not logged in
Home       Members    Calendar    Who's On

Add to briefcase

Ordering items by hierarchy without RBAR Expand / Collapse
Posted Monday, March 24, 2014 1:40 PM
SSC Eights!

SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!

Group: General Forum Members
Last Login: Tuesday, June 23, 2015 5:23 AM
Points: 833, Visits: 1,726
Hey all,

I feel like I already know the answer to this question, but it is eluding me ...

Say I have a table with two columns - ID and ParentID. Say this table has the following values:

ID ParentID
10 50
20 30
30 10

Now, say I want the following output from my query:

ID ParentID Order
10 50 2
20 30 4
30 10 3
50 NULL 1

Is there any way to get this result in a single query, without needing potentially infinite recursion or using a row-by-row comparaison?
Post #1554206
Posted Monday, March 24, 2014 2:32 PM



Group: General Forum Members
Last Login: Today @ 7:18 AM
Points: 38,561, Visits: 35,574
Sure... you could do a 4 way self join but that's hardcoding levels.

Recursion isn't so bad here. It will do things by level, not by row.

--Jeff Moden
"RBAR is pronounced "ree-bar" and is a "Modenism" for "Row-By-Agonizing-Row".

First step towards the paradigm shift of writing Set Based code:
Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column."

(play on words) "Just because you CAN do something in T-SQL, doesn't mean you SHOULDN'T." --22 Aug 2013

Favorite Quotes:
"Has anyone ever told you that a query you have written runs too fast?" - Dwain Camps - 6 Mar 2014

Helpful Links:
How to post code problems
How to post performance problems
Post #1554216
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse