Sql 服务器递归 parent/child 相同 table 使用相同字段

Sql Server Recursive parent/child same table using same field

我需要从同一个 table...parent 和所有 children 得到...

当运行这个查询时:

select location, children  from lochierarchy where parent ='HSAGCF'

这个结果:

Location    Children
--------    ------------
HSAGCFSMF   1
HSAGEE      1
HSAGGAI     0
HSAGPO      1
HSAGSA      1
HSAGSACC    1
HSAGSAFR    0
HSAGSARV    0
HSAGSASG    0
HSAGSC      1
HSAGSD      1
HSAGSI      1
HSAGSO      1
HSAGSR      0
HSAGST      0
HSAGSTTO    0

当位置有 children = 1 在层次结构中有更多 child

我如何做一个递归来获取这个查询上面的每个位置 children = 1 和 运行 再次像这样查询:

select location 
  from lochierarchy 
 where parent in ( 'HSAGCFSMF', 'HSAGEE', 'HSAGGAI', 'HSAGPO', 'HSAGSA',
                   'HSAGSACC','HSAGSAFR', 'HSAGSARV', 'HSAGSASG', 'HSAGSC',
                   'HSAGSD', 'HSAGSI', 'HSAGSO', 'HSAGSR', 'HSAGST', 
                   'HSAGSTTO', 'HSAGSV', 'HSAGU1', 'HSAGU2', 'HSAGU3', 'HSAGU4')


locations     Children
----------    ------------
HSAGCFSMF       1
HSAGEE          1
HSAGGAI         0
HSAGPO          1
HSAGSA          1
HSAGSACC        1
HSAGSAFR        0
HSAGSARV        0
HSAGSASG        0
HSAGSC          1
HSAGSD          1
HSAGSI          1
HSAGSO          1
HSAGSR          0
HSAGST          0
HSAGSTTO        0
HSAGSV          0

需要重复此递归,直到 child所有位置都为 =0

如果您使用的是 SQL 2005 或更高版本,则可以使用递归通用 table 表达式。像这样:

declare @parent varchar(20) = 'HSAGCF';

with cte as (
   select location, parent 
   from lochierarchy
   where location = @parent

   union all

   select c.location, c.parent
   from lochierarchy as c
   join cte as p
      on c.parent = p.location
)
select *
from cte;

如果你想要一条通往树中叶节点的路径,我将其留作 reader 的练习。