在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
答案 0 :(得分: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
答案 1 :(得分:0)
我建议在您的表格中使用HierarchyID
数据类型,并使用GetAncestor
方法