如何在返回表中查找父ID

时间:2012-08-07 11:29:11

标签: sql-server sql-server-2008

我有以下表格:

ID     ParentID
1         NULL
2          1
3          2
4          NULL
5          4
6          5
7          3

我想找到特定子ID的第一个ID。 示例:ID = 7,结果为1
ID = 6,结果为4

怎么做?

2 个答案:

答案 0 :(得分:4)

你需要做一些递归的CTE魔法才能解决这个问题。

如此给出表变量中的数据:

declare @data table(id int, parentid int)
insert into @data
  select 1, null
  union select 2,1
  union select 3,2
  union select 4, null
  union select 5,4
  union select 6,5
  union select 7,3

以下应该可以解决问题:

;with recursiveTable as
(
    select d.id, d.parentId, 0 as depth
    from @data d
    where d.id=6 -- Parameterize this
    union all

    select d.id, d.parentid, r.depth-1
    from @data d
    inner join recursiveTable r
    on d.id = r.parentId
)
select top 1 id 
from recursiveTable 
order by depth

如上所述插入6会返回4。将此更改为7会根据请求返回1

答案 1 :(得分:0)

试试这个:

 CREATE TABLE childpar(ID int,ParentID int)
    INSERT INTO childpar 
    values(1,NULL),
    (2, 1),
    (3, 2),
    (4, NULL),
    (5, 4),
    (6, 5),
    (7, 3)


DECLARE @inpyID int
SET @inpyID=7

;WITH CTE1 as (
select * from childpar where id=@inpyID
union all
select c2.* from CTE1 c1 inner join childpar c2 on c1.ParentID = c2.ID
)

select top 1 id from CTE1 order by id asc