SQL Server 2008:递归迭代方法

时间:2012-11-10 22:42:11

标签: sql-server sql-server-2008

想象一下名为Group的表,每个组都可以拥有'子'组,只要它们的级别较低。因此Group and childGroup表之间存在一对多的关系。

enter image description here

many-to-manyGroup之间也存在Items关系,因此Groups_Items用于保存每个表的FK。

我需要写一个查询,其中given Group keyfind all its child组,all the childs of child groupsthe customers belonging to those found groups

我知道它需要是某种类型的递归查询,但我不知道如何在SQL中完成此操作。以下是所讨论表格的结构:

enter image description here

所以,如果我在上表中设置了这些数据:

enter image description here

查询是查找For Group 1, find Its customers, Its Child groups (and their Childs) and all their customers,输出应为:

<Group> 1
    <customer> 1
    <customer> 2
    <Group> 2
        <customer> 2
        <Group> 3
        <Group> 4

有人可以告诉我这是怎么做到的吗?谢谢

1 个答案:

答案 0 :(得分:2)

我希望我理解你的问题

;WITH Hierarchy (GroupID,ID,  ParentID
               ,hLevel
               ) AS
(
   -- Base case
   (
   Select  [Parent Key] as GroupID,NULL,NULL,0
   FROM Tree
   where [Parent Key]=1
   UNION
   SELECT
      [Child Key] as GroupID,
      [Child Key] as ID,
      [Parent Key] as ParentID
      ,1 as hLevel
   FROM Tree
   where [Parent Key]=1
   ) 

   UNION ALL

   -- Recursive step
   SELECT
      e.[Child Key] as GroupID,
      e.[Child Key],
      e.[Parent Key]
     ,eh.hLevel + 1
   FROM tree e
      INNER JOIN Hierarchy eh ON
         e.[Parent Key] = eh.ID
)


Select Distinct h.GroupID, c.Name,h.ParentID as ParentGroupID
from Hierarchy h
left join test c on h.GroupID=c.ID

较旧的尝试将是

Declare @Parent int
Declare @count int
Select @Parent=??

Select cast(ID as Int) as ID
into #tmp
from Tabelle where ParentID=@Parent

select @Count=0
While @Count<(Select Count(*) from #tmp)
   begin
   Select @Count=(Select Count(*) from #tmp)
   insert into #tmp Select Cast(ID as int) from Tabelle where ParentID in (Select ID from #tmp) and ID not in (Select ID from #tmp)
   end
Select * from #tmp
Drop table #tmp