Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

sql server - Finding all Children in a Hierarchy SQL

I have a Database Hierarchy that sits somewhat like this

LHID | location     | parent
------------------------------
1    | Trim         | NULL
2    | Trim - South | Trim
3    | South-1      | Trim - South

What I need to do is select all children of Trim - South. It goes extremely deep and there are around 100 children locations and I've found ways to do it recursively but have had no luck replicating them. I know the logic of going through recursively to select all the children as I have done similar procedures in other languages, just never with SQL so I'm having trouble grasping the exact necessary syntax for it. Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...