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'

  • 相关阅读:
    log日志框架和LocationAwareLogger问题
    Eclipse 各种小图标的含义
    自定义log4j日志级别
    在Tomcat配置JNDI数据源的三种方式
    mybatis中"#"和"$"的区别
    Postman用法简介-Http请求模拟工具
    mustache模板技术(转)
    VS的编译选项
    Java Service Wrapper简介与使用
    还活着
  • 原文地址:https://www.cnblogs.com/zxh8080/p/6088264.html
Copyright © 2011-2022 走看看