【问题标题】:Please help me with this traversing query请帮我解决这个遍历查询
【发布时间】:2012-05-18 05:27:54
【问题描述】:
CatID  parID  catName
1      -1        A
2       1        B  
3       2        C
4       3        D

我想编写一个以字符串格式返回父子关系的查询。

在上表中,catName 的 parentId 为 -1,这意味着它没有父级。 B 的 parentID 为 1,这意味着 A 是它的父节点。

所以最后的字符串是这样的

A=>B=>c=>D

这就是我想要生成查询的方式。

我将传递 CatID,它会遍历直到它得到 -1。

【问题讨论】:

  • 你在使用实体框架吗?还是直接 ADO.NET?

标签: asp.net sql-server tsql


【解决方案1】:
declare @CatID int;
set @CatID = 4;

with C as
(
  select parID,
         cast(catName as varchar(max)) as catName
  from YourTable
  where CatID = @CatID
  union all
  select T.parID,
         T.catName + '=>' + C.catName
  from YourTable as T
    inner join C
      on T.CatID = C.parID
)
select catName
from C
where parID = -1

SE-Data

【讨论】:

    【解决方案2】:

    作为部分答案,听起来您需要递归查询。 Here 是一个 StackOverflow 线程,其中包含一些关于递归查询的好信息。至于如何使用查询将其变成单个字符串,我不知道……那部分可能针对编程语言进行了更优化。

    【讨论】:

      【解决方案3】:

      你需要定义函数然后在递归循环中调用它。

      您可以使用MPTT (Modified Preorder Tree Traversal) 来存储嵌套树或分层数据。

      this article 描述如何在单个查询中获取分层的“面包屑”。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-12
        • 2013-07-11
        • 2022-12-07
        • 2014-12-27
        • 1970-01-01
        • 2022-11-26
        相关资源
        最近更新 更多