0
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。

4

3 回答 3

3
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-数据

于 2012-05-18T06:01:40.400 回答
1

作为部分答案,听起来您需要递归查询。是一个 StackOverflow 线程,其中包含一些关于递归查询的好信息。至于如何使用查询将其转换为单个字符串,我不知道......那部分可能更适合编程语言。

于 2012-05-18T05:38:18.600 回答
1

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

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

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

于 2012-05-18T05:54:54.437 回答