0

在 SQL Server 2008 中;

我有一棵树。我需要获取节点 n 的所有子节点(见图)以及这些子节点的所有子节点等,直到叶节点相当琐碎。我还需要能够说'以节点 o,上树直到我们到达 m,因为 m 是节点 n 的子节点,所以将节点 o 的某些属性设置为节点 m 的某些属性。节点 o 可以是 3 层深(如图所示)或 45 层深,x 层深。

这将获取给定节点(或区域)的所有子节点

    --Return all sub-area structure of an area:

      WITH temp_areas (ParentAreaID, AreaID, [Name], [Level]) AS
      (
            SELECT ParentAreaID, AreaID, [Name], 0
            FROM lib_areas WHERE AreaID = @AreaID
            UNION ALL
            SELECT B.ParentAreaID, B.AreaID, B.[Name], A.Level + 1
            FROM temp_areas AS A, lib_areas AS B
            WHERE A.AreaID = B.ParentAreaID
      )

INSERT INTO @files (id) SELECT fileid FROM lib_filesareasxref where areaid in (select  areaid from temp_areas)

while exists (select * from @files)
begin
select top 1
@ID = id
from
@files ORDER BY id DESC

delete from @files where id = @id

树

4

2 回答 2

2

这将追溯@node_o直到它到达@node_m或到达树的顶部(如果@node_m不在上面@node_o

  WITH
    parents
  AS
  (
    SELECT
      A.ParentAreaID, A.AreaID, A.[Name], 0
    FROM
      lib_areas  AS A
    WHERE
      A.AreaID = @node_o

    UNION ALL

    SELECT
      A.ParentAreaID, A.AreaID, A.[Name], B.Level + 1
    FROM
      lib_areas  AS A
    INNER JOIN
      parents    AS B
        ON A.AreaID = B.ParentAreaID
    WHERE
      B.AreaID <> @node_m
  )
  SELECT
    *
  FROM
    parents
于 2012-07-06T09:11:00.813 回答
0

我建议HierarchyID在您的表中使用数据类型,并使用该GetAncestor方法

于 2012-07-06T09:18:11.443 回答