zoukankan      html  css  js  c++  java
  • 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 广州市
  • 相关阅读:
    [CF1037D] Valid BFS?
    [AMPPZ2014] Petrol
    [CF241E] Flights
    [洛谷P4436] HNOI/AHOI2018 游戏
    [洛谷P1613] 跑路
    [AMPPZ2014] The Captain
    [洛谷 P1373] 小a和uim之大逃离
    jq 图片切换效果 类似3D
    jq 块的拖拽效果
    sort排序问题
  • 原文地址:https://www.cnblogs.com/LYshuqian/p/2144272.html
Copyright © 2011-2022 走看看