So I know the question does not make sense in the typical parent-child relationship, but in this case the parent and children are similar to google email groups. Each group (parent) can contain multiple other groups (children), and those children can also include other parents that also are linked to one of the ancestors. This is not a problem as the goal is to just determine which users belongs to a group, the recursion is not relevant nor wrong.
The basic data is available at SqlFiddle
CREATE TABLE SQLTest (
Parent NVARCHAR(100) NULL
, Child NVARCHAR(100) NULL
)
INSERT INTO SQLTest
VALUES
('A','B'),
('B','C'),
('C','A'),
('A','D'),
('X','Y')
with the query
with x (Parent,Child) as (
select Parent, Child
from SQLTest
where Parent = 'A'
union all
select T.Parent,T.Child
from SQLTest T
join x on x.Child = T.Parent
)
select *
from x;
I was using PostgreSQL where this works as previous found records are not used for the next iteration of the join. However in SQL Server I am getting an infinite loop. I know how to stop the loop, and I also know I can make a materialized path to check for cycles, for reference see Microsoft Forums. However I am hoping there is something easier especially as I am using byte[] ulids for ids and don't really want to convert them and join and then do like. Hoping there is something easier and more performant that I am missing.
The expected output would be
A
B
C
D
Meaning just all the ids of all nodes, both the parents and children, that can be reached from A.
I am using the 2022 SQL Server version, fiddle is from an earlier version in case that matters.