使用递归查询检索结果

时间:2012-10-17 17:03:26

标签: sql sql-server sql-server-2008-r2 recursive-query

我有一个表,用其父ID保存记录版本 例如

Table(Id,version,parentId)

我试图从给定的Id值

获取所有相关记录
;WITH CTE (Id,ParentId)
AS
(
Select T1.Id,T1.ParentId
From Table T1
Where T1.ID = @Id or T1.ParentId=@Id

Union All

Select T2.Id, T2.ParentId
From Table T2
     Inner Join CTE C on C.Id= T2.ParentId  
)

这适用于提供主要父ID (162527) 时,它会带给我

Id      VersionNo   ParentId
162527      1.0         0
162530      1.1         162527
162531      1.2         162527
162532      1.2.1       162531
162533      1.2.1.1     162532
162534      1.2.2       162531
200346      1.2.2.1     162534
200354      1.2.2.1.1   200346

但是当我将 200354 作为ID传递时,它会返回给我

200346  1.2.2.1     162534
200354  1.2.2.1.1   200346

但是当我给出一个id时,我想要所有相关的记录。

任何帮助

由于

1 个答案:

答案 0 :(得分:3)

declare @Table table (id int, parentid int)

declare @id int, @ParentId int

select @id = 162530 

insert into @Table
select 162527, 0 union all
select 162530, 162527 union all
select 162531, 162527 union all
select 162532, 162531 union all
select 162533, 162532 union all
select 162534, 162531 union all
select 200346, 162534 union all
select 200354, 200346

;WITH Parents
AS
(
    Select T1.Id, T1.ParentId from @Table T1 where Id = @Id
    Union All
    Select T2.Id, T2.ParentId
    From @Table T2 Inner Join Parents C on C.ParentId = T2.Id
)
select @ParentId = P.id
from Parents as P
where parentid = 0

;WITH Children
AS
(
    Select T1.Id, T1.ParentId from @Table T1 where Id = @ParentId
    Union All
    Select T2.Id, T2.ParentId
    From @Table T2 Inner Join Children C on C.Id = T2.parentid
)
select *
from Children

上一个

;WITH Children (Id,ParentId)
AS
(
    Select T1.Id, T1.ParentId from @Table T1 where Id = @Id
    Union All
    Select T2.Id, T2.ParentId
    From @Table T2 Inner Join Children C on C.ParentId = T2.Id
),Parents (Id,ParentId)
AS
(
    Select T1.Id, T1.ParentId from @Table T1 where Id = @Id
    Union All
    Select T2.Id, T2.ParentId
    From @Table T2 Inner Join Parents C on C.Id = T2.parentId
)
select * from Parents
union
select * from Children