I have a table called SegmentCaller which saves a segment code (SegmentCaller) and the segment codes it calls (SegmentCalled), structured as below
SegmentCaller | SegmentCalled |
---|---|
SEG1 | SEG2 |
SEG1 | SEG3 |
SEG1 | SEG4 |
SEG2 | SEG5 |
SEG2 | SEG6 |
SEG3 | SEG7 |
SEG4 | SEG8 |
SEG7 | SEG9 |
SEG8 | SEG1 |
SEG9 | SEG7 |
Here is an graphical view of the data: Node graph
I need a query that will start with a segment code, for example SEG1 and continue looking for all descendants until all paths end (as illustrated in the graph above). This can go on for hundreds of levels downwards, and there is the issue of circular references, where, for example, SEG8 could call SEG1 again.
Tried using a CTE, but I am not that familiar with it. Since SegmentCaller has repeated rows for each segment, couldn't figure out how to make it work.
WITH tmp AS (
SELECT
[SegmentCaller],
[SegmentCalled]
FROM
[FOSAnalysis].[dbo].[FOSSegmentCaller]
WHERE SegmentCaller = 'SEG1'
UNION ALL
SELECT
sc.[SegmentCaller],
sc.[SegmentCalled]
FROM
[FOSAnalysis].[dbo].[FOSSegmentCaller] sc
INNER JOIN tmp o
ON o.SegmentCalled = sc.SegmentCaller
)
SELECT * FROM tmp
Using the sample code above, as seen in the table, some segments, as in the case of 2-9, are completely ignored instead of getting the descendants of each one. Also, the query above throws the following error.
The statement terminated. The maximum recursion 100 has been exhausted before statement completion.
SegmentCaller | SegmentCalled |
---|---|
SEG1 | SEG2 |
SEG1 | SEG3 |
SEG1 | SEG4 |
SEG1 | SEG5 |
SEG1 | SEG6 |
SEG1 | SEG7 |
SEG1 | SEG8 |
SEG1 | SEG9 |
SEG1 | SEG10 |
SEG10 | SEG11 |
SEG10 | SEG12 |
SEG10 | SEG13 |
SEG13 | SEG14 |
SEG13 | SEG15 |
SEG15 | SEG16 |
SEG14 | SEG16 |