Skip to content
Advertisement

RECURSIVE QUERY – PARENT/CHILD

Say I have a table like so:

Let’s say I’m always given a middle value so one that has both children and parent nodes which at this time I don’t know what they are. e.g I am given ID: 4. I have written a recursive query which gets me both the Parents and the child records but I’m quite unsure if it the CORRECT method of going about it but also if its the quickest.

This is working with how i want the results to come back so will return id: 01,02,03,04,06 as they are either a parent or child of the ID 04 etc.

Essentially what I wished to get at was what is the best way of doing a recursive query to get both parent and child of a given record, where to find the children you must use 1 column and to get parents must use another etc.

Advertisement

Answer

This is Pseudo SQL terms, but you only need 2 CTEs, and no DISTINCT to get what you are after. Transversing hierachical data, that doesn’t use the hierachyid datatype is never going to be as effecient as it could be, as you need recursion.

Anyway, you would effectively just want this:

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement