How to order by name, then by parent ID

  • It's been a while since I've done any TSQL and seem to be stuck at something simple. I have the following table definition:

    CategoryID,

    CategoryName,

    ParentCategoryID

    How do I order the results by CategoryName, then by ParentCategoryID?

    So my data would probably look something like this:

    CatID CatName ParentCatID

    1 Parent 1 NULL

    2 Child 1 1

    3 Child 2 1

    5 Child 3 1

    4 Parent 2 NULL

    6 Child 1 4

    7 Child 2 4

    I have mixed the order of CatID on purpose, as the order should always be CatName, ParentCatID.

    Ideally, I'd like the CatName to be in alphabetical order for the Child categories as well...

    Thanks,

  • Untested, but try this

    WITH CTE(CategoryID,ParentCategoryID,CategoryName,fullpath) AS (

    SELECT CategoryID,ParentCategoryID,CategoryName,CAST(CategoryName AS VARCHAR(MAX))

    FROM mytable

    WHERE ParentCategoryID IS NULL

    UNION ALL

    SELECT p.CategoryID , p.ParentCategoryID ,p.CategoryName, c.fullpath+'/'+CAST(p.CategoryName AS VARCHAR(MAX))

    FROM CTE c

    INNER JOIN mytable p ON p.ParentCategoryID=c.CategoryID)

    SELECT CategoryID,CategoryName,ParentCategoryID

    FROM CTE

    ORDER BY fullpath

    ____________________________________________________

    Deja View - The strange feeling that somewhere, sometime you've optimised this query before

    How to get the best help on a forum

    http://www.sqlservercentral.com/articles/Best+Practices/61537
  • Works perfectly, thanks.

    Think this will go in a stored procedure rather than trying to figure out how to write this in LINQ...

Viewing 3 posts - 1 through 2 (of 2 total)

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