Hi @nd0911
If I understand correctly, you can try this query.
create or alter function [dbo].[fn_Tree](@ID int)
returns table
as
return(
with t1 as(
select child from tbl where parent = @id
union all
select b.child from t1 as a inner join tbl as b
on b.parent = a.child
),t2 as(
select child from t1
union all
select d.parent from t2 as c inner join tbl as d
on d.child = c.child
),t3 as(
select child from t2
union all
select f.child from t3 as e inner join tbl as f
on f.parent = e.child
),t4 as(
select parent from tbl where child = @id
union all
select h.parent from t4 as g inner join tbl as h
on h.child = g.parent
),t5 as(
select parent from t4
union all
select j.child from t5 as i inner join tbl as j
on j.parent = i.parent
),t6 as(
select parent from t5
union all
select l.parent from t6 as k inner join tbl as l
on l.child = k.parent
),t7 as(
select parent from t6
union all
select n.child from t7 as m inner join tbl as n
on n.parent = m.parent)
select @id as Root,child as 'Relateds Ids' from t3
union
select @id,parent from t7)
Best regards,
Percy Tang
----------
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.