2013-07-11 147 views
2

我已经写了CT与CT。存储过程与CTE查询类别,子类别,子子类别

CREATE PROC [dbo].[CategoryListShow] 
@id AS INT 
AS 
WITH CategoryList 
AS 
(
    SELECT parent.Categoryid, CONVERT(varchar(50),parent.CategoryName) 
    as 
    Name, parent.CategoryParentid 
    FROM Category as parent 
    WHERE parent.CategoryParentid IS NULL 

    UNION ALL 

    SELECT child.Categoryid, CONVERT(varchar(50),CL.Name + ' > ' + child.CategoryName) 
    as Name, child.CategoryParentid 
    FROM Category as child 

    INNER JOIN CategoryList as CL ON child.CategoryParentid = CL.Categoryid 

    WHERE child.CategoryParentid IS NOT NULL 
) 
    SELECT Name from CategoryList option (maxrecursion 0) 

我该如何达到理想的输出?例如,如果用户键入id = 14111然后输出应该是这样的:Everything Else > Test Auctions > General

我的表结构:

感谢

回答

2

你可以做到这一点

;with 
CTE_Data as 
(
    select C.CategoryID, cast(C.CategoryName as nvarchar(max)) as CategoryName 
    from Category as C 
    where C.CategoryID = C.CategoryParentId 

    union all 

    select C.CategoryID, CD.CategoryName + ' > ' + C.CategoryName 
    from Category as C 
     inner join CTE_Data as CD on CD.CategoryID = C.CategoryParentId 
    where C.CategoryID <> C.CategoryParentId 
) 
select * 
from CTE_Data 
where CategoryID = @ID 

或其他方式:

;with 
CTE_Data as 
(
    select C.CategoryID, cast(C.CategoryName as nvarchar(max)) as CategoryName, C.CategoryParentId 
    from Category as C 
    where C.CategoryID = @ID 

    union all 

    select C.CategoryID, cast(C.CategoryName as nvarchar(max)) + ' > ' + CD.CategoryName, C.CategoryParentId 
    from Category as C 
     inner join CTE_Data as CD on CD.CategoryParentId = C.CategoryID 
    where CD.CategoryID <> C.CategoryID 
) 
select CategoryName 
from CTE_Data 
where CategoryID = CategoryParentId 

SQL FIDDLE

+0

我收到此错误:类型不锚和递归查询的列“类别名称”,“CTE_Data”递归部分之间的匹配。 –

+0

尝试编辑查询,我已经添加了'cast' –

+0

感谢作品像一个魅力。 –