Getting depth-first traversal insted of breadth first in T-SQL

限于喜欢 提交于 2021-02-11 16:55:55

问题


I have the following T-SQL function: https://gist.github.com/cwattengard/11365802

This returns data in a breadth-first traversal. Is there a simple way to make this function return its data in a depth-first traversal? I have a treeview-component that excpects this (legacy system).

I already have a similar stored procedure that returns the tree in a depth-first traversal, but it's using cursors and is really slow. (6-7 seconds as opposed to this function that takes less than a second on the same data).


回答1:


I think I just had a eureka moment. If I add the Path variable already supplied by the CTE, and sort by that, I get what I want. The OrgID is a unique ID. So ordering by it would make it sort by the expected output for the user (chronologically) and be depth-first for the treeview.




回答2:


 http://sqlanywhere.blogspot.in/2012/10/example-recursive-union-tree-traversal.html

Here's a diagram showing the primary keys for a tree-structured table:

                           1
                           |
       ---------------------------------------
       2            93            4          5       
       |             |            |          |
--------------  ------------  --------     ------  
6  7  8  9  10  11 12 13  14  15 16 17     18  19
   |                   |             |      |
 -----               -----         -----  -----
 27 26               25 24         23 22  21 20

Here's what the breadth-first and depth-first queries should return:

Breadth-First  Depth-First
1              1
2              2
93             6
4              7
5              27
6              26
7              8
8              9
9              10
10             93
11             11
12             12
13             13
14             25
15             24
16             14
17             4
18             15
19             16
27             17
26             23
25             22
24             5
23             18
22             21
21             20
20             19



回答3:


If you order the output by tekst will that do it?

First populate a table variable @unsorted inside the function; then finally return Select * from @unsorted order by tekst?




回答4:


I know this is very late to the game, but seems like you could use hierarchyid to get a nice depth first search...

The github file referenced in the op appears to have gone missing, but the basic formula is

  1. Put hierarchyid::GetRoot() as Foo in your CTE anchor query
  2. Put cast (cte.Foo.ToString() + cast(row_number() over(order by ) as varchar) + '/' as hierarchyid) as Foo in your recursive query
  3. order By Foo when you invoke the CTE

and the results come out depth first



来源:https://stackoverflow.com/questions/23336520/getting-depth-first-traversal-insted-of-breadth-first-in-t-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!