Here is my data structure look like a tree of nodes that I keep all of them in one recursive table:
Id | Name | ParentId | Level
-----------------------------------
1 | Node1 | NULL | 1
2 | Node2 | NULL | 1
3 | Node3 | 1 | 2
4 | Node4 | 1 | 2
5 | Node5 | 3 | 3
6 | Node6 | 3 | 3
7 | Node7 | 3 | 3
8 | Node8 | 4 | 3
9 | Node9 | 6 | 4
10 | Node10 | 6 | 4
11 | Node11 | 8 | 4
12 | Node12 | 10 | 5
The problem that I have is retrieve children and parents of one Node is not performed very well, I tried to call the recursive function to fetch the children and parents. for example for Node6
retrieveAllChildrenof(6){} -> return 9,10,12;
retrieveAllParentsof(6){} -> return 3,1;
So I just thinking to add a new column to avoid recursive function, something like this:
Id | Name | ParentId | Level | Trace
---------------------------------------------
1 | Node1 | NULL | 1 | 1
2 | Node2 | NULL | 1 | 2
3 | Node3 | 1 | 2 | 1-3
4 | Node4 | 1 | 2 | 1-4
5 | Node5 | 3 | 3 | 1-3-5
6 | Node6 | 3 | 3 | 1-3-6
7 | Node7 | 3 | 3 | 1-3-7
8 | Node8 | 4 | 3 | 1-4-8
9 | Node9 | 6 | 4 | 1-3-6-9
10 | Node10 | 6 | 4 | 1-3-6-10
11 | Node11 | 8 | 4 | 1-4-8-11
12 | Node12 | 10 | 5 | 1-3-6-10-12
Now with trace field I could retrieve the children and parents as:
retrieveAllChildrenof(6){} ->
//Trace(6) = 1-3-6; GetAllNodesThatStartWithTrace(1-3-6) => 9,10,12;
retrieveAllParentsof(6){} -> //Trace(6) = 1-3-6; GetNodesIdsIn(1-3); => 1,3;
I know the comma-separated or dash-separated data is hard to process but is there any better way to navigate in nodes and find children and parents, any suggestion?
UPDATE Currently for recursive functions I used like this: CTE Recursion to get tree hierarchy