sql-server - 使用 CTE 的存储过程来查询 Category 、 Sub Category 、 Sub Sub Category

标签 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

我的表结构:

谢谢

最佳答案

你可以这样做

;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

关于sql-server - 使用 CTE 的存储过程来查询 Category 、 Sub Category 、 Sub Sub Category,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17592868/

相关文章:

MySQL 说 : Documentation #1064 - You have an error in your SQL syntax; on Stored Procedure

mysql - 在mysql中插入一个计数过程

c# - 架构 ASP.NET MVC 5

sql-server - SQL Server : How to select all days in a date range even if no data exists for some days

python - 如何从 Docker 容器中的 python 脚本连接到 Ubuntu 上的本地 SQL 服务器

mysql - 处理级联删除: Are there ways to do this automatically in mySQL

sql-server - 只有 sysadmin 固定服务器角色的成员才能执行此操作。 Azure SQL Server 数据库与 SQL Server 数据库

c# - Entity Framework SQL Server 错误消息语言

c# - Microsoft.sqlserver.Management.Smo 的 CLSID 和 PROG ID 是什么

MySQL 过程忽略 LEAVE 语句?