SQL DEMO
WITH Path ( FromID, ToID, Length, nodes ) AS (
SELECT t1.FromID, t1.ToID, 0 as Length,
CAST( t1.FromID AS VARCHAR(max) ) +'-'+
CAST( t1.ToID AS VARCHAR(max) ) as nodes
FROM Table1 t1
UNION ALL
SELECT P.FromID, t2.ToID, P.Length + 1,
P.nodes + '-' + CAST(t2.ToID AS VARCHAR(max) ) as nodes
FROM Table1 t2
JOIN Path P
ON P.ToID = t2.FromID
)
SELECT *
FROM Path
WHERE FromID = 1
and ToID = 17
Order by Length
OUTPUT
From 1 to 17 there is a tie with two path with length 2
| FromID | ToID | Length | nodes |
|--------|------|--------|-----------|
| 1 | 17 | 0 | 1-17 |
| 1 | 17 | 1 | 1-8-17 |
| 1 | 17 | 1 | 1-5-17 |
| 1 | 17 | 2 | 1-5-13-17 |
| 1 | 17 | 2 | 1-8-13-17 |