使用CTE存储过程来查询类别,子类别,子子类别

时间:2013-07-11 12:02:40

标签: sql-server stored-procedures

我用CTE写了一个SP。

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

我的表结构:

由于

1 个答案:

答案 0 :(得分: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