I have a self reference table to store hierarchical values in order to show up them in a TreeView or so on ,according to James Crowley article (Tree structures in ASP.NET and SQL Server)
Our table would look something like this:
Id ParentId Name Depth Lineage
1 NULL Root Node 0 /1/
2 1 Child A 1 /1/2/
3 1 Child B 1 /1/3/
4 1 Child C 1 /1/4/
5 2 Child D 2 /1/2/5/
To get path of a node (for example id=5) he suggest following query against table
SELECT *
FROM dfTree
WHERE (SELECT lineage
FROM dfTree
WHERE id = 5) LIKE lineage + '%'
result would be :
Id ParentId Name Depth Lineage
1 NULL Root Node 0 /1/
2 1 Child A 1 /1/2/
5 2 Child D 2 /1/2/5/
And Is Acceptable
But how about to have a result set when there are multiple IDs which i want to have their path ? therefore for example in above example instead of Id=5 i would like to pass multiple values something like this :
SELECT *
FROM dfTree
WHERE (SELECT lineage
FROM dfTree
WHERE id IN (5,6,8,9)) LIKE lineage + '%'
But the above statement make no sense and it is invalid sql server expression
How could i solve this problem ?
Thanks in advance
This query…
…returns the following result on your test data:
As you can see, all paths are “merged” together – for example, the path component
Id=1belongs to both the path:/1/4/and the path:/1/2/5/, yet exists in the result set only once.One the other hand, if you do need to distinguish between different paths, you’d need to do something like this:
Result:
In this case, each path is identified by its leaf. This assumes there are no diamond-shaped dependencies (i.e. this is a real tree and not just any DAG); if there are, then you’d need to use
T1.Lineageinstead ofT1.Idto identify the path.