我有一个包含2列(id,childId)的表,其中包含以下数据:
我有以下CTE获取记录并且工作正常。
DECLARE @id TABLE (id int, childId int);
INSERT INTO @id SELECT 1, 2;
INSERT INTO @id SELECT 2, 4;
INSERT INTO @id SELECT 3, 5;
INSERT INTO @id SELECT 4, 6;
INSERT INTO @id SELECT 5, null;
INSERT INTO @id SELECT 6, null;
WITH cte AS
(
SELECT id, childId
FROM @id
WHERE id = 1
UNION ALL
SELECT b.id, b.childId
FROM @id b
INNER JOIN cte
ON b.id = cte.childId
)
SELECT * FROM cte
但是,我想添加锚点详细信息,以便结果如下所示:
这样第3列就是主要的锚记录。
这可能吗?
答案 0 :(得分:0)
char
提供测试代码:
WITH cte AS
(
SELECT id, childId, id AS anchorId
FROM mytable
WHERE
id IN (SELECT id FROM @id)
UNION ALL
SELECT b.id, b.childId, cte.anchorId
FROM mytable b
INNER JOIN cte
ON b.id = cte.childId
)
SELECT
id
, childId
, case
WHEN id = anchorId THEN NULL
ELSE anchorId
END as anchorId
FROM cte
答案 1 :(得分:0)
只需在CTE中添加一个thrid列。
declare @mytable table ( id int, childId int );
insert @mytable
( id, childId )
values ( 1, 2 ),
( 2, 4 ),
( 3, 5 ),
( 4, 6 ),
( 5, null ),
( 6, null );
declare @id table ( id int );
insert into @id
select 1;
insert into @id
select 3;
with cte
as ( select id ,
childId ,
id root
from @mytable
where id in ( select id
from @id )
union all
select b.id ,
b.childId ,
cte.root
from @mytable b
inner join cte on b.id = cte.childId
)
select *
from cte;