You can use a recursive CTE:
WITH CTE
AS(
SELECT 1 AS relationLevel, child.*
FROM dbo.TableName child
WHERE child.parent = 'Trim - South'
UNION ALL
SELECT relationLevel+1, parent.*
FROM CTE nextOne
INNER JOIN dbo.TableName parent ON parent.parent = nextOne.location
)
SELECT * FROM CTE ORDER BY relationLevel
Result:
RELATIONLEVEL LHID LOCATION PARENT
1 3 South-1 Trim - South
1 4 South-2 Trim - South
2 4 South-2-1 South-2
DEMO
Maybe you want to travserse from the parent to the children, then use this:
WITH CTE
AS(
SELECT 1 AS relationLevel, parent.*
FROM dbo.TableName parent
WHERE parent.location = 'Trim - South'
UNION ALL
SELECT relationLevel + 1, child.*
FROM CTE nextOne
INNER JOIN dbo.TableName child ON child.parent = nextOne.location
)
SELECT * FROM CTE ORDER BY relationLevel
Result:
RELATIONLEVEL LHID LOCATION PARENT
1 2 Trim - South Trim
2 3 South-1 Trim - South
2 4 South-2 Trim - South
3 4 South-2-1 South-2
DEMO
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…