zoukankan      html  css  js  c++  java
  • 树状sql--采用递归方式获取节点

    创建数据库

    create table City
    (
    id varchar(3) primary key ,
    pid varchar(3) ,
    name varchar(10)
    )

    插入数据

    insert into City values('001' , null , '广东省');
    insert into City values('002' , '001' , '广州市');
    insert into City values('003' , '001' , '深圳市') ;
    insert into City values('004' , '002' , '天河区') ;
    insert into City values('005' , '003' , '罗湖区');
    insert into City values('006' , '003' , '福田区') ;
    insert into City values('007' , '003' , '宝安区') ;
    insert into City values('008' , '007' , '西乡镇') ;
    insert into City values('009' , '007' , '龙华镇');
    insert into City values('010' , '007' , '松岗镇');

    insert into City values('011' , null , '中国');  

    递归子节点的存储过程:

    create proc ProcCity
    @id nvarchar(36)
    as
    begin
    with cte as
    (
    select a.id,a.name,a.pid from City a where id=@id
    union all
    select k.id,k.name,k.pid from City k inner join cte c on c.id = k.pid
    )select * from cte
    end

    获取深圳以及深圳的所有区:exec ProcCity '003'

    递归父节点的存储过程:

    create proc ProcCity
    @id nvarchar(36)
    as
    begin
    with cte as 

    select a.id,a.name,a.pid from City a where id=@id 
    union all 
    select k.id,k.name,k.pid from City k inner join cte c on k.id = c.pid 
    )select * from cte 
    end

    获取深圳以及深圳的所有父节点:exec ProcCity '003'

  • 相关阅读:
    POJ 3672 水题......
    POJ 3279 枚举?
    STL
    241. Different Ways to Add Parentheses
    282. Expression Add Operators
    169. Majority Element
    Weekly Contest 121
    927. Three Equal Parts
    910. Smallest Range II
    921. Minimum Add to Make Parentheses Valid
  • 原文地址:https://www.cnblogs.com/zxh8080/p/6088264.html
Copyright © 2011-2022 走看看