SQL 根据子节点查询所有父节点

createtable tb(id varchar(3) , pid varchar(3) , name varchar(10))
insertinto tb values('001' , null , '广东省')
insertinto tb values('002' , '001' , '广州市')
insertinto tb values('003' , '001' , '深圳市')
insertinto tb values('004' , '002' , '天河区')
insertinto tb values('005' , '003' , '罗湖区')
insertinto tb values('006' , '003' , '福田区')
insertinto tb values('007' , '003' , '宝安区')
insertinto tb values('008' , '007' , '西乡镇')
insertinto tb values('009' , '007' , '龙华镇')
insertinto tb values('010' , '007' , '松岗镇')
go

--查询指定节点及其所有父节点的函数
createfunction f_pid(@idvarchar(3)) returns@t_leveltable(id varchar(3))
as
begin
insertinto@t_levelselect@id
select@id= pid from tb where id =@idand pid isnotnull
while@@ROWCOUNT>0
begin
insertinto@t_levelselect@idselect@id= pid from tb where id =@idand pid isnotnull
end
return
end
go

--调用函数查询002(广州市)及其所有父节点
select a.*from tb a , f_pid('002') b where a.id = b.id orderby a.id
/*
id pid name
---- ---- ----------
001 NULL 广东省
002 001 广州市
原文地址:https://www.cnblogs.com/LYshuqian/p/2144272.html