SQL 中实现递归(根据子节点查找父节点)

1,数据库2005之前,使用函数实现。(根据子节点查找父节点)

if object_id('f_getParentBySon') is not null drop function f_getParentBySon
GO
CREATE function f_getParentBySon(@id varchar(100))
RETURNS @t table(id varchar(100))
as
begin
insert into @t select @id
select @id= Parid from BOM_Detail where id= @id and Parid is not null --第一次执行,将id=输入的id 所在数据全部查出,然后将父id赋给变量(目的是当同一个子id参与了多个父商品的构造时查出所有的父商品)
while @@ROWCOUNT > 0
begin
insert into @t select @id select @id = Parid from BOM_Detail where id= @id and Parid is not null --查询出已经被父商品赋值的变量的新数据,并再次将新数据的父产品赋给变量进行查询,直至无数据查询跳出循环
end
return
end
go

使用:select  a.*  from BOM_Detail a , f_getParentBySon('000020000600005') b where a.id= b.id 

2,数据库2005之后,借助 with  as 语句(目的仍然是根据子节点查找父节点)

 ;WITH subqry AS
  (
    SELECT  tb.id, tb.qty, tb.parid FROM   tb  WHERE id=@id  
    UNION ALL
    SELECT  tb.id, tb.qty, tb.parid FROM  tb,subqry
    WHERE tb.id= subqry.Parid
   )

select * from subqry  --查询数据

关于with as demo的实例,借助大神的一篇文章https://www.cnblogs.com/hshuai/p/3947424.html

原文地址:https://www.cnblogs.com/zhh-blogs/p/11648804.html