Click here to monitor SSC
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 


Hierarchy Structure SQL Query


Hierarchy Structure SQL Query

Author
Message
Jeff Moden
Jeff Moden
SSC-Forever
SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)

Group: General Forum Members
Points: 45464 Visits: 39948
dwain.c (5/24/2012)
Jeff Moden (5/24/2012)
dwain.c (5/24/2012)
...so what makes you think I could do so here?


Not sure. You DO have a love for rCTEs and I'm thinking that you'll pull a rabbit out of your hat just because you do love working with them.


Actually I think you're confusing my exploration with love.

I have kind of a fondness/hate relationship with them.

I'm fond of them because they're cool and interesting. I hate them because mostly they don't perform so well and because I am recursively challenged. And also because I haven't found that killer app yet (but will keep on looking).


I'm recursively challenged, as well. I've been married more than once. :-P

--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.
Although they tell us that they want it real bad, our primary goal is to ensure that we dont actually give it to them that way.
Although change is inevitable, change for the better is not.
Just because you can do something in PowerShell, doesnt mean you should. Wink

Helpful Links:
How to post code problems
How to post performance problems
Forum FAQs
RBarryYoung
RBarryYoung
SSCrazy Eights
SSCrazy Eights (9.5K reputation)SSCrazy Eights (9.5K reputation)SSCrazy Eights (9.5K reputation)SSCrazy Eights (9.5K reputation)SSCrazy Eights (9.5K reputation)SSCrazy Eights (9.5K reputation)SSCrazy Eights (9.5K reputation)SSCrazy Eights (9.5K reputation)

Group: General Forum Members
Points: 9456 Visits: 9517
Jeff Moden (5/24/2012)
dwain.c (5/24/2012)
Jeff Moden (10/24/2010)
For the simple task of sorting in the correct order, we'll use the "Hierarchical Path" method. To build it, we'll use a "Recursive CTE". Look that up in Books Online for a better understanding of them. I will tell you right now that they are NOT a panacea. Hierarchies are one of the few places where I don't mind the use of recursive CTE's because they're normally RBAR code. In the example that follows, the recursive CTE is "layered" or (as Celko calls it), "lasagna" code. It processes a full set (one full level) of information for each iteration which makes it non-RBAR code. It's still a bit slower than a more lengthy method but it takes a huge hierarchy to really appreciate the difference so the recursive CTE is usually good enough.


Oh my! No fair! I love posting recursive CTE solutions and you beat me to it.


Only by a year and eight months. :-) (Just having a little fun here).

Shifting gears, Dwaine, all is not lost here. If you could figure out a way to make this kind of "lasagne" recursive CTE faster, I know a lot of people (especially me) that would greatly appreciate it. The only other way that I know to build the Hierarchical path is with a slightly faster While Loop and even though it's not a RBAR While Loop, it still doesn't sit so well with me that I have to use one here.


Jeff, could you post this as a challenge, along with a test set? I'd love to take a whack at it.

-- RBarryYoung, (302)375-0451 blog: MovingSQL.com, Twitter: @RBarryYoung
Proactive Performance Solutions, Inc.
"Performance is our middle name."
Jeff Moden
Jeff Moden
SSC-Forever
SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)

Group: General Forum Members
Points: 45464 Visits: 39948
You mean just as a separate post or here or did you have something else in mind, Barry?

--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.
Although they tell us that they want it real bad, our primary goal is to ensure that we dont actually give it to them that way.
Although change is inevitable, change for the better is not.
Just because you can do something in PowerShell, doesnt mean you should. Wink

Helpful Links:
How to post code problems
How to post performance problems
Forum FAQs
RBarryYoung
RBarryYoung
SSCrazy Eights
SSCrazy Eights (9.5K reputation)SSCrazy Eights (9.5K reputation)SSCrazy Eights (9.5K reputation)SSCrazy Eights (9.5K reputation)SSCrazy Eights (9.5K reputation)SSCrazy Eights (9.5K reputation)SSCrazy Eights (9.5K reputation)SSCrazy Eights (9.5K reputation)

Group: General Forum Members
Points: 9456 Visits: 9517
Jeff Moden (5/26/2012)
You mean just as a separate post or here or did you have something else in mind, Barry?


Right, a separate post, with a data set (million rows, of course) and a formal statement of the challenge ("fastest execution time to produce result set like this ...".

I actually have a fair start on the data set...

-- RBarryYoung, (302)375-0451 blog: MovingSQL.com, Twitter: @RBarryYoung
Proactive Performance Solutions, Inc.
"Performance is our middle name."
Jeff Moden
Jeff Moden
SSC-Forever
SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)

Group: General Forum Members
Points: 45464 Visits: 39948
RBarryYoung (5/26/2012)
Jeff Moden (5/26/2012)
You mean just as a separate post or here or did you have something else in mind, Barry?


Right, a separate post, with a data set (million rows, of course) and a formal statement of the challenge ("fastest execution time to produce result set like this ...".

I actually have a fair start on the data set...



Got it. I'll see what i can do. Thanks, Barry.

--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.
Although they tell us that they want it real bad, our primary goal is to ensure that we dont actually give it to them that way.
Although change is inevitable, change for the better is not.
Just because you can do something in PowerShell, doesnt mean you should. Wink

Helpful Links:
How to post code problems
How to post performance problems
Forum FAQs
tafinami
tafinami
Forum Newbie
Forum Newbie (3 reputation)Forum Newbie (3 reputation)Forum Newbie (3 reputation)Forum Newbie (3 reputation)Forum Newbie (3 reputation)Forum Newbie (3 reputation)Forum Newbie (3 reputation)Forum Newbie (3 reputation)

Group: General Forum Members
Points: 3 Visits: 2
To get hierarchy and tree data
tafinami
tafinami
Forum Newbie
Forum Newbie (3 reputation)Forum Newbie (3 reputation)Forum Newbie (3 reputation)Forum Newbie (3 reputation)Forum Newbie (3 reputation)Forum Newbie (3 reputation)Forum Newbie (3 reputation)Forum Newbie (3 reputation)

Group: General Forum Members
Points: 3 Visits: 2
DECLARE c CURSOR READ_ONLY FAST_FORWARD FOR
SELECT Id FROM Tree_Table WHERE Id NOT IN (SELECT DISTINCT ParentId FROM Tree_Table WHERE ParentId IS NOT NULL)

DECLARE @IdPk INT
OPEN c
FETCH NEXT FROM c INTO @IdPk
WHILE (@@FETCH_STATUS = 0)
BEGIN
DECLARE @NodeValue VARCHAR(MAX)
SET @NodeValue = ''
WHILE(EXISTS(SELECT * FROM Tree_Table WHERE Id=@IdPk))
BEGIN
SELECT @NodeValue=Name+'/'+@NodeValue,
@IdPk=ParentId
FROM Tree_Table
WHERE id=@IdPk
END
PRINT 'Parent to Leaf: ' + LEFT(@NodeValue,LEN(@NodeValue)-1)
FETCH NEXT FROM c INTO @IdPk
END
CLOSE c
DEALLOCATE c

To get hierarchy and tree view data
Jeff Moden
Jeff Moden
SSC-Forever
SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)

Group: General Forum Members
Points: 45464 Visits: 39948
tafinami (6/30/2014)
DECLARE c CURSOR READ_ONLY FAST_FORWARD FOR
SELECT Id FROM Tree_Table WHERE Id NOT IN (SELECT DISTINCT ParentId FROM Tree_Table WHERE ParentId IS NOT NULL)

DECLARE @IdPk INT
OPEN c
FETCH NEXT FROM c INTO @IdPk
WHILE (@@FETCH_STATUS = 0)
BEGIN
DECLARE @NodeValue VARCHAR(MAX)
SET @NodeValue = ''
WHILE(EXISTS(SELECT * FROM Tree_Table WHERE Id=@IdPk))
BEGIN
SELECT @NodeValue=Name+'/'+@NodeValue,
@IdPk=ParentId
FROM Tree_Table
WHERE id=@IdPk
END
PRINT 'Parent to Leaf: ' + LEFT(@NodeValue,LEN(@NodeValue)-1)
FETCH NEXT FROM c INTO @IdPk
END
CLOSE c
DEALLOCATE c

To get hierarchy and tree view data


In this case, a cursor isn't the worst thing in the world. However, take a look at the following articles...
http://www.sqlservercentral.com/articles/Hierarchy/94040/
http://www.sqlservercentral.com/articles/T-SQL/94570/

--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.
Although they tell us that they want it real bad, our primary goal is to ensure that we dont actually give it to them that way.
Although change is inevitable, change for the better is not.
Just because you can do something in PowerShell, doesnt mean you should. Wink

Helpful Links:
How to post code problems
How to post performance problems
Forum FAQs
Jeff Moden
Jeff Moden
SSC-Forever
SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)

Group: General Forum Members
Points: 45464 Visits: 39948
Jeff Moden (5/27/2012)
RBarryYoung (5/26/2012)
Jeff Moden (5/26/2012)
You mean just as a separate post or here or did you have something else in mind, Barry?


Right, a separate post, with a data set (million rows, of course) and a formal statement of the challenge ("fastest execution time to produce result set like this ...".

I actually have a fair start on the data set...



Got it. I'll see what i can do. Thanks, Barry.


Wow... talking about a forgotten promise... my apologies, Barry.

That, notwithstanding, please see the following article which also has a million row "clean" hierarchy generator.

http://www.sqlservercentral.com/articles/Hierarchy/94040/

This next one is part of the same series (2 articles in the series) and provides an alternate to all of the currently known hierarchical structures.
http://www.sqlservercentral.com/articles/T-SQL/94570/

--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.
Although they tell us that they want it real bad, our primary goal is to ensure that we dont actually give it to them that way.
Although change is inevitable, change for the better is not.
Just because you can do something in PowerShell, doesnt mean you should. Wink

Helpful Links:
How to post code problems
How to post performance problems
Forum FAQs
dwain.c
dwain.c
SSCarpal Tunnel
SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)SSCarpal Tunnel (4.3K reputation)

Group: General Forum Members
Points: 4291 Visits: 6431
Jeff Moden (6/30/2014)
tafinami (6/30/2014)
DECLARE c CURSOR READ_ONLY FAST_FORWARD FOR
SELECT Id FROM Tree_Table WHERE Id NOT IN (SELECT DISTINCT ParentId FROM Tree_Table WHERE ParentId IS NOT NULL)

DECLARE @IdPk INT
OPEN c
FETCH NEXT FROM c INTO @IdPk
WHILE (@@FETCH_STATUS = 0)
BEGIN
DECLARE @NodeValue VARCHAR(MAX)
SET @NodeValue = ''
WHILE(EXISTS(SELECT * FROM Tree_Table WHERE Id=@IdPk))
BEGIN
SELECT @NodeValue=Name+'/'+@NodeValue,
@IdPk=ParentId
FROM Tree_Table
WHERE id=@IdPk
END
PRINT 'Parent to Leaf: ' + LEFT(@NodeValue,LEN(@NodeValue)-1)
FETCH NEXT FROM c INTO @IdPk
END
CLOSE c
DEALLOCATE c

To get hierarchy and tree view data


In this case, a cursor isn't the worst thing in the world. However, take a look at the following articles...
http://www.sqlservercentral.com/articles/Hierarchy/94040/
http://www.sqlservercentral.com/articles/T-SQL/94570/


Or this one, if Jeff's wonderful solutions on steroids overwhelm you:

The Performance of Traversing a SQL Hierarchy


My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!

My thought question: Have you ever been told that your query runs too fast?

My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.


Need to UNPIVOT? Why not CROSS APPLY VALUES instead?
Since random numbers are too important to be left to chance, let's generate some!
Learn to understand recursive CTEs by example.
Splitting strings based on patterns can be fast!
My temporal SQL musings: Calendar Tables, an Easter SQL, Time Slots and Self-maintaining, Contiguous Effective Dates in Temporal Tables
Go


Permissions

You can't post new topics.
You can't post topic replies.
You can't post new polls.
You can't post replies to polls.
You can't edit your own topics.
You can't delete your own topics.
You can't edit other topics.
You can't delete other topics.
You can't edit your own posts.
You can't edit other posts.
You can't delete your own posts.
You can't delete other posts.
You can't post events.
You can't edit your own events.
You can't edit other events.
You can't delete your own events.
You can't delete other events.
You can't send private messages.
You can't send emails.
You can read topics.
You can't vote in polls.
You can't upload attachments.
You can download attachments.
You can't post HTML code.
You can't edit HTML code.
You can't post IFCode.
You can't post JavaScript.
You can post emoticons.
You can't post or upload images.

Select a forum

































































































































































SQLServerCentral


Search