1

我有一个表,它用他们的父 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 时,我想要所有相关的记录。

任何帮助

谢谢

4

1 回答 1

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
于 2012-10-17T17:05:50.030 回答