bom結構,查詢節點下所有子節點

2021-04-27 17:42:44 字數 1597 閱讀 9308

--bom結構,查詢節點下所有子節點:

create table os(id int,parentid int,desn varchar(10))

insert into os select 1,0,'體育用品'

insert into os select 2,0,'戶外運動'

insert into os select 3,1,'籃球'

insert into os select 4,1,'足球'

insert into os select 5,2,'帳篷'

insert into os select 6,2,'登山鞋'

insert into os select 7,0,'男士用品'

insert into os select 8,7,'刮鬍刀'

insert into os select 9,3,'大號籃球'

--求個節點下所有子節點:

create function f_cid(@id int)

returns varchar(500)

asbegin

declare @t table(id int,parentid int,desn varchar(10),lev int)

declare @lev int

set @lev=1

insert into @t select *,@lev from  os where id=@id

while(@@rowcount>0)

begin

set @lev=@lev+1

insert into @t select a.*,@lev from os a,@t b

where a.parentid=b.id and b.lev=@lev-1

enddeclare @cids varchar(500)

select @cids=isnull(@cids+',','')+ltrim(id) from @t order by lev

return @cids

endgo

--呼叫函式

select *,ids=dbo.f_cid(id) from os

--得到每個節點路徑:

create proc wsp2

@id int

asselect *,cast(' ' as varchar(10)) fullpath  into #os from os

declare @i int,@j int

set @i=0

set @j=1

select @i=max(parentid) from #os

update #os set fullpath=id

while @j<=@i

begin

update #os set fullpath=a.fullpath+','+ltrim(#os.id)

from #os inner join #os a on #os.parentid=a.id

where #os.parentid=@j

set @j=@j+1

endselect * from #os

go--呼叫儲存過程

exec wsp2 1

同步刪除被刪除節點的所有子節點 BOM節點刪除

create table tb id int,pid int,name nvarchar 10 insert tb select1,null,山東省 union allselect2,1,煙台市 union allselect4,2,招遠市 union allselect3,1,青島市 union ...

根據子節點遞迴查詢所有父節點

有個需求,需要根據給定的子節點向上遞迴查詢所有父節點,網上查詢了一些,但是都不是很滿意,有的是需要用到全域性變數定義儲存列表,但是會有併發問題,然後自己手寫乙個 test void contextloads1 public listgetpid listidlist,integer pid,list...

MySQL遞迴查詢所有子節點,樹形結構查詢

delimiter drop procedure if exists findlchild iid 遞迴父節點 layer 允許遞迴深度 create procedure findlchild iid bigint 20 layer bigint 20 begin 建立接受查詢的臨時表 create...