Build menu with CTE ....

  • The "NM" stands for "Never Mind". I had posted a rebuttal saying that the code didn't sort alphabetically, which seemed logical to me at the time. Then I realized that it did sort by the given ID using the same sort method that I had in my first article on hierarchies, compared it to the order the OP was looking for, and realized my mistake. I removed my mistaken post and, since we can't delete posts, just put in a quick "NM".

    Still, it is a nice method... especially since I've used the same method in the past. 🙂

    --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.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • hunchback (9/23/2013)


    I changed [path] by order_val in the recursive part and now it should run flawless.

    A recursive CTE is still an iterative approach so I do not hold my breath hoping for better performance.

    You can add a clustered index by ID and a nonclustered by IdRoot.

    Well said. Oddly enough, a well constructed WHILE loop that iterates over the Levels of the menu in a manner similar to the rCTE would probably do as well. In either case, the recursion is necessary and isn't as bad as an rCTE that counts because the rCTE method that we both used (and a similar WHILE loop would use) processes an entire set (all nodes at a given level) instead of just individual rows.

    --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.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

Viewing 2 posts - 16 through 16 (of 16 total)

You must be logged in to reply to this topic. Login to reply