I have following data
| From | To |
+------+----+
| 1 | 2 |
| 2 | 3 |
| 2 | 4 |
| 5 | 1 |
| 6 | 5 |
| 5 | 7 |
+------+----+
Now I would like to query my data with CTE enhanced select, like
DECLARE @start INT;
SET @start = 1;
DECLARE @depth INT;
SET @depth = 1;
WITH
[Recursive] AS
(
SELECT
1 as [level],
*
FROM [dbo].[myTable]
WHERE @start IN ([From], [To])
UNION ALL
SELECT
t1.[level] + 1,
t2.*
FROM [Recursive] t1
JOIN [dbo].[myTable] t2
ON t1.[level] < @depth
AND
(
t1.[From] IN (t2.[From], t2.[To])
OR t1.[To] IN (t2.[From], t2.[To])
)
)
SELECT DISTINCT
[From],
[To]
FROM [Recursive]
With this small test-data the performance is quite ok – but when increasing the data and depth the execution gets really bad (caused by multiple-column join).
What is the correct statement for such a task?
As I use C# on my client-side, I ended up pulling all the data to the client and to the graph-calculation-stuff in C#. It’s way more performant and as memory-footprint is not the problem, I am happy with that 🙂