随心所欲地构建它,就像计算级别一样:
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
要将路径显示为网页上的链接,您需要同时显示类别名称和链接中使用的相应 ID。一个简单的分隔符,允许您使用字符串拆分功能,例如this,简化了显示代码:
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
注意:这假设竖线(“|”)不能出现在类别名称中。
ASP.NET 代码将需要拆分两个路径字符串并将它们一起向下走,从而在运行过程中创建链接。一个方便的显示分隔符是“»”(U+00BB:右双角引号)。
可以将所有代码添加到查询中以生成所需的 HTML,但这不是它所属的地方。