1. 程式人生 > >[SQL]T-Sql 遞歸查詢(給定節點查所有父節點、所有子節點的方法)

[SQL]T-Sql 遞歸查詢(給定節點查所有父節點、所有子節點的方法)

select IT rod nbsp pos UC with var 數據


-- 查找所有父節點
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

[SQL]T-Sql 遞歸查詢(給定節點查所有父節點、所有子節點的方法)