tsql breadcrumb查询

时间:2012-09-14 05:41:39

标签: sql tsql

enter image description here我有以下CTE查询

;WITH cte AS (
    SELECT 0 AS lvl, id, catName, parent,
        CAST(id AS VARCHAR(128)) AS Sort
    FROM CategoriesMap WHERE id =2
    UNION ALL
    SELECT p.lvl + 1, c.id, c.catName, c.parent,
        CAST(CAST(c.id AS VARCHAR) + '_' + p.Sort   AS VARCHAR(128))
    FROM CategoriesMap c
    INNER JOIN cte p ON p.parent = c.id
)
select * from cte

排序(树)列具有这样的输出(对于两行)......

2
1_2

其中,2是类别电视,1_2表示这是树形图(1: Internet Tv, 2 = Jadoo Tv)

现在我可以使用类别代码返回类别名称吗?

类似

2:Jadoo Tc

1_Internet Tv: 2_Jadoo Tv

由于

2 个答案:

答案 0 :(得分:2)

;WITH cte AS (
    SELECT 0 AS lvl, id, catName, parent,
        CAST(CAST(id AS VARCHAR(128)) + ':' + catName AS VARCHAR(128)) AS Sort
    FROM CategoriesMap WHERE id =2
    UNION ALL
    SELECT p.lvl + 1, c.id, c.catName, c.parent,
        CAST(CAST(c.id AS VARCHAR) + ':' + c.catName + '_' + p.Sort AS VARCHAR(128))
    FROM CategoriesMap c
    INNER JOIN cte p ON p.parent = c.id
)
select * from cte

答案 1 :(得分:0)

;WITH cte AS (
    SELECT 0 AS lvl, id, catName, parent,
        CAST(id AS VARCHAR(128)) AS Sort
    FROM CategoriesMap WHERE id =2
    UNION ALL
    SELECT p.lvl + 1, c.id, c.catName, c.parent,
        CAST(CAST(c.id AS VARCHAR) + '_'+c.catName+':' + p.Sort   AS VARCHAR(128))
    FROM CategoriesMap c
    INNER JOIN cte p ON p.parent = c.id
)
select * from cte