SqlServer中递归查询父节点及其所属子节点
需求场景
递归查询父节点及其所属子节点
SQL脚本实现-根据子节点查询所有的父节点
-- 查找所有父节点
with tab as
(
select pc.id,pc.ParentId,pcd.Name,1 as [level] from ProductCategories pc join ProductCategoryDescriptions pcd on pcd.ProductCategoryId=pc.Id and pcd.LanguageId='en' --where id=1--子节点
union all
select a.id--当前节点Id
,b.ParentId,--父节点Id
c.Name --父节点名称,关联可以修改为【a.Id=c.ProductCategoryId】就表示当前节点名称
,a.[level]+1--层级
from
tab a,--子节点数据集
ProductCategories b , --父节点数据集
ProductCategoryDescriptions c --父节点数据集
where a.ParentId=b.Id and b.Id=c.ProductCategoryId and c.LanguageId='en' --子节点数据集.parendID=父节点数据集.ID
)
select * from tab where id=149;
查询结果
这里的Level是倒序的,也就是当前数据为第一层,level的大小由father、ancestors一次递增,max(level)表示祖先
SQL脚本实现-根据父节点查询所有的子节点
-- 根据父节点查找所有子节点
with a as (
select id, parentid from ProductCategories where id=124
union all
select x.id, x.parentid from ProductCategories x,a where x.parentid=a.id
)
select * from a
查询结果
这里的Level是倒序的,也就是当前数据为第一层,level的大小由father、ancestors一次递增,max(level)表示祖先