0

嗨,我需要一个查询来执行此操作我的表数据

ID        ParentID         DATA
--------------------------------
1             -1             a
2              1             b
3              2             c
4              3             d
5              3             f

什么需要一个以 ID 作为参数并返回所有recursively childsItself

parameter : (ID=2)

返回必须是:

ID        ParentID         DATA
--------------------------------
2              1             b
3              2             c
4              3             d
5              3             f
4

4 回答 4

3

试试这个:

;with temp as (
  select id, parentId, data from t
  where id = 2
  union all
  select t.id, t.parentId, t.data from t
  join temp on temp.id = t.parentId
)
select * from temp

在这里拉小提琴。

于 2012-04-11T16:31:17.290 回答
2

这应该为你做:

create table #temp 
(
    id int, 
    parentid int,
    data varchar(1)
)
insert #temp (id, parentid, data) values (1, -1, 'a')
insert #temp (id, parentid, data) values (2,1, 'b')
insert #temp (id, parentid, data) values  (3,2, 'c')
insert #temp (id, parentid, data) values  (4,3, 'd')
insert #temp (id, parentid, data) values  (5,3, 'f')

; with cte as (
    select  id, parentid, data, id as topparent
    from    #temp
    union all
    select  child.id, child.parentid, child.data, parent.topparent
    from    #temp child
    join    cte parent
    on      parent.id = child.parentid

)
select  id, parentid, data
from    cte
where topparent = 2

drop table #temp

编辑或者你可以把WHERE子句放在第一个里面select

create table #temp 
(
    id int, 
    parentid int,
    data varchar(1)
)
insert #temp (id, parentid, data) values (1, -1, 'a')
insert #temp (id, parentid, data) values (2,1, 'b')
insert #temp (id, parentid, data) values  (3,2, 'c')
insert #temp (id, parentid, data) values  (4,3, 'd')
insert #temp (id, parentid, data) values  (5,3, 'f')

; with cte as (
    select  id, parentid, data, id as topparent
    from    #temp
    WHERE id = 2
    union all
    select  child.id, child.parentid, child.data, parent.topparent
    from    #temp child
    join    cte parent
    on      parent.id = child.parentid

)
select  id, parentid, data
from    cte

drop table #temp

结果:

id  parentid      data
2   1              b
3   2              c
4   3              d
5   3              f
于 2012-04-11T16:28:27.933 回答
1
declare @ID int = 2;

with C as
(
  select ID, ParentID, DATA
  from YourTable
  where ID = @ID
  union all
  select T.ID, T.ParentID, T.DATA
  from YourTable as T
    inner join C 
      on T.ParentID = C.ID
)
select ID, ParentID, DATA
from C

试用SE-Data

于 2012-04-11T16:30:01.477 回答
0

试试这个。

select * from table where id= 2 or parentid = 2
于 2012-04-11T16:13:01.640 回答