Sql Server获取指定ID的所有父节点ID

数据库结构

IDPid
10
21
32
42
51

Sql语句

if exists (select * from sys.procedures where name='GetPidByID')
	drop procedure GetPidByID
go
create procedure  GetPidByID
(
@ID int
)
as
declare @resultTable table(Pid int)--结果表
declare @selectTable table(ID int)--每一次查询结果表
declare @whereTable table(ID int)--上一次条件查询表
insert @whereTable values(@ID)--添加查询条件

while 1=1 --进入循环,不由它控制循环结束
begin
	insert into @selectTable
	select t.Pid from [表名] t join @whereTable r on t.ID=r.ID group by t.pid --按上一次条件查询表进行查询pid
	
	if  not exists(select * from @selectTable where ID = 0) and exists(select * from @selectTable) --判断是否查到根节点pid=0,或者无数据
	begin
		--没有到根节点
		insert into @resultTable select * from @selectTable --将本次查询结果添加到结果表中
		delete @whereTable --删除上一次条件查询表中的数据
		insert into @whereTable select * from @selectTable --将本次查询结果添加到上一次条件查询表中,以便下次查询
	end
	else
		break--到达根节点,退出循环
end
select * from @resultTable group by pid --除去重复数据

------储存过程在此截止------
--执行
exec GetPidByID 4
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值