mysql获取当前节点的所有叶子节点_mssql sqlserver 如何获取一个叶子节点下所有子节点呢?...

摘要:

下文sql技巧—获取所有子节点的方法分享,如下所示;

实现思路:

通过while循环依次遍历节点,然后将起添加到临时表中返回

即可通过节点获取所有子节点

例:

create table [maomao365.com]

(keyId int,parentId int,n nvarchar(10))

go

insert into [maomao365.com]

(keyId,parentId,n)values

(1,0,'总经办'),

(2,1,'销售部'),

(3,1,'财务部'),

(4,1,'客服部'),

(5,2,'销售1部'),

(6,2,'销售2部')

go

/*

创建获取所有子节点的sql函数

*/

CREATE FUNCTION [dbo].[fn_getTreeAll]

(

@keyId int

)

RETURNS @a table(keyId int,n nvarchar(10))

AS

begin

insert into @a(keyId,n)

select keyId,n from [maomao365.com]

where keyId =@keyId

while exists(select null from [maomao365.com]

where parentId in (select keyid from @a)

and keyId not in (select keyId from @a)

)

begin

insert into @a(keyId,n)

select keyId,n from [maomao365.com]

where parentId in (select keyid from @a)

and keyId not in (select keyId from @a)

end

return;

end;

go

select * from [dbo].[fn_getTreeAll](2)

go

drop FUNCTION [dbo].[fn_getTreeAll]

go

truncate table [maomao365.com]

drop table [maomao365.com]

go

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值