1

親ID Egでレコードのバージョンを維持するテーブルがあります

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

しかし、IDとして200354を渡すと、返されます

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 に答える