Sql server 使用CTE查询类别、子类别、子类别的存储过程
我用CTE写了一个SPSql server 使用CTE查询类别、子类别、子类别的存储过程,sql-server,stored-procedures,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.CategoryParenti
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,那么输出应该是:其他所有内容>测试拍卖>常规
我的表格结构:
谢谢你能做到的
;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
我得到了这个错误:递归查询CTE_数据的列CategoryName中的锚和递归部分之间的类型不匹配。