在 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