I need to develop a good table structure for creating a sortable multilevel list using SQL Server Database.
Here is an example of the way I develop sortable multilevel lists:
A
├──B
| ├──E
| ├──F
| ├──O
|
├──C
| ├──M
|
My table structure:
ID Title Parent Sort
---------------------------
1 A Null 0
2 B A 0
3 E B 0
4 F B 1
5 O B 2
6 C A 1
7 M C 0
Now, would you mind telling me the best way of developing such lists?
Thank you very much indeed.
Just go with your outlined structure. SQL Server supports recursive queries via CTEs, something like this will do the trick for you:
I’m building some extra informative fields here:
level, indicating depth of the node from the root;path, which is built based on yoursortfield and is used to sort the tree properly;fullname— just a nice view on the full node name.You can try this query here.
Please, consider the size of your data — for huge data structures you might want to push predicates into the inner query for better performance.