当前位置:首页 » 编程语言 » 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
--递归调用,不知道是否想要这样

热点内容
数据库job 发布:2025-07-01 11:24:51 浏览:614
怎么查微信访问记录 发布:2025-07-01 11:14:34 浏览:125
css3源码 发布:2025-07-01 11:14:33 浏览:332
android访问本机 发布:2025-07-01 10:56:06 浏览:412
服务器改id是什么 发布:2025-07-01 10:30:03 浏览:612
php微信开发教程 发布:2025-07-01 10:28:24 浏览:843
访问学者联系导师 发布:2025-07-01 10:27:44 浏览:985
服务器端的http地址 发布:2025-07-01 10:04:35 浏览:177
php好处 发布:2025-07-01 10:01:45 浏览:879
安卓车机什么屏幕好 发布:2025-07-01 09:46:15 浏览:549