當前位置:首頁 » 編程語言 » sql查詢父節點所有子節點

sql查詢父節點所有子節點

發布時間: 2025-05-09 15:53:19

sql根據子節點查出所有的父節點的

用函數做,根據你的表結構改:
父節點查詢子節點
create function GetChildID(@ParentID int)
returns @t table(ID int)
as
begin
insert into @t select id from table where parent_id = @ParentID
while @@rowcount<>0
begin
insert into @t select a.id from table as a
inner join @t as b
on a.parent_id = b.ID
and not exists(select 1 from @t where ID=a.ID)
end
return
end
go

子節點查詢父節點
create function GetParentID(@ChildID int)
returns @t table(PID int)
as
begin
insert into @t select parent_id from table where ID=@ChildID
while @@rowcount<>0
begin
insert into @t select a.parent_id from table as a
inner join @t as b
on a.ID=b.PID
and not exists(select 1 from @t where PID=a.parent_id)
end
return
end
go

Ⅱ SQL語句查詢出父節點下的所有子節點


createtable##tmp_users(idint,usernamenvarchar(255),parentidint)
declare@IDint
select@ID=idfromt_Userstwhereexists
(select*fromt_Userst2wheret2.id=t.parentidandt2.username='user1')
execAddSons@ID
select*from##tmp_users
droptable##tmp_users


--存儲
createprocereAddSons@idint
as
ifexists(select*fromt_Userswhereparentid=@id)
begin
declare@tmp_IDint
declarecurcursorfor
selectidfromt_Userswhereparentid=@id
opencur
fetchnextfromcurinto@tmp_ID
while@@FETCH_STATUS=0
begin
insertinto##tmp_users
select*fromt_Userstwhereid=@tmp_ID
ifexists(select*fromt_Userswhereparentid=@tmp_ID)
begin
execAddSons@tmp_ID
end
fetchnextfromcurinto@tmp_ID
end
closecur
DEALLOCATEcur
end
--遞歸調用,不知道是否想要這樣

熱點內容
頑固的緩存 發布:2025-07-01 03:28:23 瀏覽:114
u盤插安卓手機上怎麼加密 發布:2025-07-01 03:09:19 瀏覽:90
php記住我 發布:2025-07-01 02:58:51 瀏覽:392
流媒體伺服器搭建php 發布:2025-07-01 02:54:24 瀏覽:371
我的世界伺服器地板方塊 發布:2025-07-01 02:41:35 瀏覽:564
魔域伺服器爆滿怎麼進 發布:2025-07-01 02:31:42 瀏覽:739
c語言統計字元出現的次數 發布:2025-07-01 02:27:24 瀏覽:242
江鈴福特主要有哪些車型以及配置 發布:2025-07-01 02:23:10 瀏覽:25
格式化資料庫 發布:2025-07-01 02:15:03 瀏覽:267
蘇州資料庫 發布:2025-07-01 02:09:25 瀏覽:617