You can perform the use of CTE, in particular rCTE.
See this and this for more information .
Example:
WITH sampleCTE (id, parent, value, depth)
AS (
SELECT id
, parent
, value
, 0
FROM
WHERE id = @targetId
UNION ALL
SELECT child.id
, child.parent
, child.value
, sampleCTE.depth + 1
FROM
INNER JOIN sampleCTE ON sampleCTE.id = child.parent
)
source
share