在没有游标的情况下在SQL中展平SQL分层数据结构

时间:2012-11-07 23:47:02

标签: sql sql-server sql-server-2008 hierarchical-data

假设我有下表

SectionID ParentIDSection DatumID
   1           NULL         1
   2            1           2
   3            1           3
   4            2           4

现在,让我假装我想选择SectionID = 1下的所有DatumID,即使它是其后代子女的一部分,这样我就可以

SectionID DatumID
  1         1
  1         2
  1         3
  1         4

是否可以在没有使用游标递归地迭代第一个表的情况下进行此操作?

3 个答案:

答案 0 :(得分:5)

这让我困惑了一分钟,因为它与我对递归的看法有相反的方向,但我想出了这个非常简单的解决方案:

;WITH Rollups AS (
    SELECT SectionId, ParentIdSection, DatumId
    FROM SectionDataTable
    UNION ALL
    SELECT parent.SectionId, parent.ParentIdSection, child.DatumId
    FROM SectionDataTable parent 
    INNER JOIN Rollups child ON child.ParentIdSection = parent.SectionId
)
SELECT *
FROM Rollups 
WHERE SectionID = 1

(替换为您想要的部分ID)

答案 1 :(得分:2)

declare @demo table
(
    SectionId int not null primary key clustered
    , ParentId int null --foreign key references @demo(SectionId)
    , DatumId int
);

insert @demo
      select 1, null, 1
union select 2, 1, 2
union select 3, 1, 3
union select 4, 2, 4
union select 5, null, 5
union select 6, 5, 6
;

with demoHierarchy
as
(
    select SectionId
    , SectionId ParentId
    , SectionId OriginalAncestorId
    , DatumId
    from @demo
    where ParentId is null --remove this line if you want OriginalAncestorId to be AnyAncestorId (if that doesn't make sense, try it and see)

    union all

    select d.SectionId
    , d.ParentId
    , h.OriginalAncestorId
    , d.DatumId
    from @demo d
    inner join demoHierarchy h
    on d.ParentId = h.SectionId
    where d.ParentId is not null --implied by the join, but here to make it explicit
)
select OriginalAncestorId SectionId
, DatumId 
from demoHierarchy
where OriginalAncestorId = 1 --not needed given your sample data only contains this data, but required when you have multiple root ancestors

此处提供有关分层查询的更多信息:http://blog.sqlauthority.com/2012/04/24/sql-server-introduction-to-hierarchical-query-using-a-recursive-cte-a-primer/

答案 2 :(得分:1)

您可以在MS SQL 2008中使用层次结构ID。另一个问题是SQL Server 2008 Hierarchy Data Type Performance?处的相对性能问题。

以下是处理递归层次结构的另一个参考:http://www.bimonkey.com/2009/09/handling-recursive-hierarchies-in-sql-server/