使用递归遍历树结构 [英] Traversing a tree structure using recursion
问题描述
什么是最好的方式循环访问此数据,以便我可以将其添加到如下列表:
- item1
- item2
>>项目2.1
>>>>项目2.1.1
>>项目2.2
- item3
等
编辑 - 当我说列表时,我的意思就像一个列表框
edit2 - woops,是的,列表需要按照父记录按字母顺序排序。我正在使用mssql。
SQL Server 2008允许您在表中定义层次结构:
您还可以使用递归CTE:
I am dealing with one table on the database. The columns are: id, name, parent_id, hasChildren. (parent_id would be an id on the table. if parent_id is null, the record is a parent.)
What would be the best way to loop through this data so I can add it to a list like:
- item1
- item2
>> item 2.1
>>>> item 2.1.1
>> item 2.2
- item3
etc etc.
edit - when i say "list" i mean like a listbox
edit2 - woops, yes, list needs to be sorted by parent record alphabetically. i'm using mssql.
SQL Server 2008 allows you to define hierarchies in a table:
- http://msdn.microsoft.com/en-us/magazine/cc794278.aspx
- Question about SQL Server HierarchyID depth-first performance
You could also use a recursive CTE:
这篇关于使用递归遍历树结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!