• SQL CTE 递归 查询省,市,区


     IF OBJECT_ID('tb') IS NOT NULL 
      DROP TABLE tb
    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
    SELECT * FROM tb AS t
    
    DECLARE @ID VARCHAR(3) 
    --查询ID = '001'的所有子节点
    SET @ID = '007'
    ;WITH Temp AS (
      SELECT id,pid,NAME FROM tb AS t WHERE t.id=@ID
      UNION ALL
      SELECT t2.id,t2.pid,t2.NAME FROM tb t2 INNER JOIN Temp tm on t2.pid=tm.ID
    )
    SELECT * FROM Temp AS t WHERE id!=@ID
  • 相关阅读:
    20190905-3 命令行和控制台编程
    作业要求 20181009-9 每周例行报告
    每周例行报告
    单元测试,结对
    四则运算试题生成
    代码规范,结对要求
    规格说明书-吉林市2日游
    功能测试
    每周例行报告2
    get与post请求的区别
  • 原文地址:https://www.cnblogs.com/gguozhenqian/p/3797222.html
Copyright © 2020-2023  润新知