mssql语句递归查找所有下级

if exists (select * from sys.all_objects where name='GetOrgTree')
begin
drop function GetOrgTree
end
go
create function GetOrgTree (@OrgID int)
returns @tb table (id int,Orgname varchar(20),ParentID int)
as
begin
--注意这里的表名是上面新建的表 tb_menu
--这条语句是插入跟@OrgName相同的这条记录 这里假设是天津
insert @tb select id,OrgName,ParentID from tabOrg where id = @OrgID
--返回受上一语句影响的行数
while @@rowcount > 0
-- 将上次的ID做为查询条件在进行插入操作,
--父ID在@tb中 现在@tb中的ID为 3 因为上面是天津 即where pid in (3)
--并且id 不在@tb中 and id not in (3)
--这里需要大家理解下
insert @tb
select id,OrgName,ParentID from tabOrg
where ParentID in (select id from @tb)
and id not in (select id from @tb)
--最后返回@tb
return
end

--select * from dbo.GetOrgTree(1)

转载于:https://www.cnblogs.com/SilenceTom/p/5575982.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值