I have a table Person that has 3 columns: Id, Name, ParentId where ParentId is the Id of the parent row.
Currently, to display the entire tree, it would have to loop through all child elements until there’s no more child elements. It doesn’t seem too efficient.
Is there a better and more efficient way to query this data?
Also, is there a better way to represent this tree like structure in a SQL Server database? An alternative design for my table/database?
I don’t think there’s anything wrong with the design, assuming you have a limited level of parent-child relationships. Here is a quick example of retrieving the relationship using a recursive CTE:
Don’t forget to clean up:
This might be a useful article. An alternative is
hierarchyidbut I find it overly complex for most scenarios.