可能な解決策の一つ:
declare @TableA table
(
ID int,
ParentID int NULL,
Name varchar(100)
)
insert into @TableA(ID, ParentID, Name)
values
(1, NULL, 'root 1'),
(2, NULL, 'root 2'),
(3, 2, 'node 3->2'),
(4, 1, 'node 4->1'),
(5, 4, 'node 5->4->1'),
(6, 3, 'node 6->3->2'),
(7, 4, 'node 7->4->1'),
(8, 7, 'node 8->7->4->1')
;with QueryA as
(
/* your query could be here */
select t.ID, t.Name
from @TableA t
where t.ID in (1, 3, 8)
),
Tree as
(
select t.ID, t.ParentID, t.Name,
case when t.ParentID is NULL then t.ID end as RootID
from @TableA t
/* starting from rows we have in QueryA */
where t.ID in (select q.ID from QueryA q)
union all
select tt.ID, t.ParentID, t.Name,
case when t.ParentID is NULL then t.ID end as RootID
from @TableA t
/* recursion to parents */
inner join Tree tt on tt.ParentID = t.ID
)
select q.ID, q.Name, t.Name as RootName
from QueryA q
inner join Tree t on t.ID = q.ID and t.RootID is not NULL
order by 1, 2
また、あなたが釜から始めることができますQueryAにリンクせずにツリーを分割する(テーブル全体)。少しシンプルに見えます。この場合、最後のステートメントでのみQueryAを参照します。
このクエリは何ですか?ストアドプロシージャ?ビュー?ただプレーンSQL? –
Zoher:単純なSQLクエリです。 – Daniel
クエリを投稿できますか? –