-- 查找所有父节点 with tab as ( select Type_Id,ParentId,Type_Name from Sys_ParamType_V2_0 where Type_Id=316--子节点 union all select b.Type_Id,b.ParentId,b.Type_Name from tab a,--子节点数据集 Sys_ParamType_V2_0 b --父节点数据集 where a.ParentId=b.Type_Id --子节点数据集.parendID=父节点数据集.ID ) select * from tab; -- 查找所有子节点 with tab as ( select Type_Id,ParentId,Type_Name from Sys_ParamType_V2_0 where Type_Id=1--父节点 union all select b.Type_Id,b.ParentId,b.Type_Name from tab a,--父节点数据集 Sys_ParamType_V2_0 b--子节点数据集 where b.ParentId=a.Type_Id --子节点数据集.ID=父节点数据集.parendID ) select * from tab; --查找从子节点到定级节点的路径 with tab as ( select Type_Id,ParentId,Type_Name,cast(Type_Id as varchar(100)) as fulltypeid from SKU_ProductType where Type_Id=423--子节点 union all select b.Type_Id,b.ParentId,b.Type_Name, cast(a.fulltypeid+','+cast(b.Type_Id as nvarchar(100)) as varchar(100)) as fulltypeid from tab a,--子节点数据集 SKU_ProductType b --父节点数据集 where a.ParentId=b.Type_Id --子节点数据集.parendID=父节点数据集.ID ) select * from tab ; --------------结果-------------- 423 410 蜂花粉 423 410 347 蜂产品 423,410 347 5 营养食品 423,410,347 5 0 健康保健 423,410,347,5
实际
WITH tree AS( SELECT ID,PID,0 as level,cast(ID as varchar(1000)) fullid,CAST(AREA_NAME as varchar(1000)) fullname FROM YUN_BASE_AREA WHERE PID='0' UNION ALL SELECT child.ID,child.PID,parent.level+1,cast(fullid+','+child.ID as varchar(1000)) fullid,cast(fullname+'>'+child.AREA_NAME as varchar(1000)) fullid FROM YUN_BASE_AREA as child inner join tree parent on parent.ID=child.PID ) SELECT * FROM tree order by fullname select * from YUN_BASE_AREA where AREA_NAME='亚洲'
结果