SQL:给定一条记录,如何在不知道层次结构中级别数的情况下查找其所有关联的子记录?

克瑞克

我有一个包含ID和ParentID的表。我需要找到给定记录的所有相关子记录。

SQL FIddle示例

要么

 Create table #Temp
(
    ID varchar(10)
   ,ParentID varchar(10)
   ,Name varchar(20)
)

Insert into #Temp
    values
     ('001','002','a')
    ,('002','003','b')
    ,('003',NULL,'c')
    ,('004','003','d')
    ,('005','002','e')
    ,('006','005','f')
    ,('007','008','g')
    ,('008','006','h')
    ,('009','005','i')
    ,('010','009','j')
    ,('011','005','k')
    ,('012','010','l')
    ,('013','010','m')

例如,给定ID ='005',我想查找其所有子记录。

Results would be ID 006,008,009,010,011,012,013

任何想法表示赞赏。

圆胡子

这是递归cte的示例,它为您提供了答案:

; with cte as (

  select ID, parentid, name from temp where parentid = '005'

  union all

  select t.ID, t.parentid, t.name from temp t
  join cte c on c.id=t.parentid
)

select * from cte

看到小提琴:http ://sqlfiddle.com/#!6/ 0e74d/4

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

Related 相关文章

热门标签

归档