打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
SQL Server根据子节点查询所有父节点的代码示例
create table tb(id varchar(3) , pid varchar(3) , name varchar(10))  
  insert into tb values('001' , null , '广东省')  
  insert into tb values('002' , '001' , '广州市')  
  insert into tb values('003' , '001' , '深圳市')  
  insert into tb values('004' , '002' , '天河区')  
  insert into tb values('005' , '003' , '罗湖区')  
  insert into tb values('006' , '003' , '福田区')  
  insert into tb values('007' , '003' , '宝安区')  
  insert into tb values('008' , '007' , '西乡镇')  
  insert into tb values('009' , '007' , '龙华镇')  
  insert into tb values('010' , '007' , '松岗镇')  
  go  
  --查询指定节点及其所有父节点的函数  
  create function f_pid(@id varchar(3)) returns @t_level table(id varchar(3))  
  as  
  begin  
  insert into @t_level select @id  
  select @id = pid from tb where id = @id and pid is not null  
  while @@ROWCOUNT > 0  
  begin  
  insert into @t_level select @id select @id = pid from tb where id = @id and pid is not null  
  end  
  return  
  end  
  go  
  --调用函数查询002(广州市)及其所有父节点  
  select a.* from tb a , f_pid('002') b where a.id = b.id order by a.id  
  /*  
  id pid name   
  ---- ---- ----------   
  001 NULL 广东省  
  002 001 广州市 
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
树形结构表查询
mysql递归查询组织机构
【程序员必备】sql语句大全
精彩SQL收藏
MySQL连接查询索引优化
生产库mysql大表分区方案
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服