Kaan Kılıç
Kaan Kılıç

Reputation: 27

Hierarchical Category sorting with subCategory's ID

I have problem about the hierarchical category sort in mssql.I have sql code that lists category with their level in the following code segment.

WITH TempCtgry (CtgryID, CtgryName, ParentCtgryId, Lvl)AS (SELECT CategoryID,CategoryName ,ParentCatID, 0 as Level FROM Category r WHERE r.ParentCatID IS NULL UNION ALL SELECT r1.CategoryID, r1.CategoryName, r1.ParentCatID, TempCtgry.Lvl+1 FROM Category r1 INNER JOIN TempCtgry on r1.ParentCatID= TempCtgry.CtgryID) SELECT * FROM TempCtgry

But I want to show sub category's parents.For Example: Television >> Smart >> Lcd Tv

How can I do that?

Thanks and King Regards!

Upvotes: 0

Views: 695

Answers (1)

HABO
HABO

Reputation: 15841

Build it up as you go, just like counting levels:

WITH TempCtgry ( CtgryID, CtgryName, ParentCtgryId, Lvl ) AS (
  SELECT CategoryID, CategoryName, ParentCatID, 0 as Level,
    Convert( VarChar(1024), CategoryName ) as Path
    FROM Category r
    WHERE r.ParentCatID IS NULL
  UNION ALL
  SELECT r1.CategoryID, r1.CategoryName, r1.ParentCatID, TempCtgry.Lvl + 1,
    Convert( VarChar(1024), Path + ' >> ' + r1.CategoryName ) as Path
    FROM Category r1 INNER JOIN
      TempCtgry on r1.ParentCatID = TempCtgry.CtgryID
  )
  SELECT *
    FROM TempCtgry

To display the path as links on a web page, you'll want to have both the category names for display and the corresponding ids for use in the links. A simple separator that allows you to use a string split function, e.g. this, simplifies the display code:

WITH TempCtgry ( CtgryID, CtgryName, ParentCtgryId, Lvl ) AS (
  SELECT CategoryID, CategoryName, ParentCatID, 0 as Level,
    Convert( VarChar(1024), CategoryName ) as Path,
    Convert( VarChar(1024), CategoryID ) as PathIds
    FROM Category r
    WHERE r.ParentCatID IS NULL
  UNION ALL
  SELECT r1.CategoryID, r1.CategoryName, r1.ParentCatID, TempCtgry.Lvl + 1,
    Convert( VarChar(1024), Path + '|' + r1.CategoryName ) as Path,
    Convert( VarChar(1024), PathIds + '|' + Convert( VarChar(9), CategoryId ) ) as PathIds
    FROM Category r1 INNER JOIN
      TempCtgry on r1.ParentCatID = TempCtgry.CtgryID
  )
  SELECT *
    FROM TempCtgry

Note: This assumes that a vertical bar ("|") cannot occur in a category name.

The ASP.NET code will need to split both path strings and walk down them together creating links as it goes. A convenient display separator is "»" (U+00BB: Right-Pointing Double Angle Quotation Mark).

It is possible to add all of the code to generate the required HTML into the query, but that isn't where it belongs.

Upvotes: 1

Related Questions