--查询树状结构某节点的上级所有根节点。
with cte_root(id,parentId,name)
as
(
--起始条件
select id,parentId,name
from table_name
where id=100001 --列出子节点查询条件
union all
--递归条件
select a.id ,a.parentId ,a.name
from table_namea
inner join
cte_root b --执行递归,这里就要理解下了
on a.id=b.parentId --根据基础表条件查询子节点(a.ID),通过CTE递归找到其父节点(b.ParentID)。
) --可以和下面查询子节点的cte_child对比。
select *,stuff((select '_' + name from cte_root order by parentId asc for xml path('')),1,1,'') as allName from cte_root where id=100001
;
select *,stuff((select '_' + name from cte_root for xml path('')),1,1,'') as allName from table2
--查询树状结构某节点下的所有子节点。
with cte_child(ID,ParentID,NAME)
as
(
--起始条件
查询树状结构某节点的上级所有根节点,查询树状结构某节点下的所有子节点
最新推荐文章于 2023-05-18 21:00:00 发布