Hierarchical Category sorting with subCategory's ID

喜夏-厌秋 提交于 2019-12-12 01:13:55

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/16369122/hierarchical-category-sorting-with-subcategorys-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!