zoukankan      html  css  js  c++  java
  • 无限极分类sql数据库的设计

     --创建测试数据表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
     
    
    
    --创建查询指定节点及其所有子节点的函数f_cid
    create function f_cid(@ID varchar(3)) returns @t_level table(id varchar(3) , level int)
    as
    begin
      declare @level int
      set @level = 1
      insert into @t_level select @id , @level
      while @@ROWCOUNT > 0
      begin
        set @level = @level + 1
        insert into @t_level select a.id , @level
        from tb a , @t_Level b
        where a.pid = b.id and b.level = @level - 1
      end
      return
    end
    go
     
    
    --调用函数查询001(广东省)及其所有子节点
    select a.* from tb a , f_cid('001') b where a.id = b.id order by a.id
    /*
    id   pid  name       
    ---- ---- ---------- 
    001  NULL 广东省
    002  001  广州市
    003  001  深圳市
    004  002  天河区
    005  003  罗湖区
    006  003  福田区
    007  003  宝安区
    008  007  西乡镇
    009  007  龙华镇
    010  007  松岗镇
     
    (所影响的行数为 10 行)
    */
     
    --调用函数查询002(广州市)及其所有子节点
    select a.* from tb a , f_cid('002') b where a.id = b.id order by a.id
    /*
    id   pid  name       
    ---- ---- ---------- 
    002  001  广州市
    004  002  天河区
     
    (所影响的行数为 2 行)
    */
     
    --调用函数查询003(深圳市)及其所有子节点
    select a.* from tb a , f_cid('003') b where a.id = b.id order by a.id
    /*
    id   pid  name       
    ---- ---- ---------- 
    003  001  深圳市
    005  003  罗湖区
    006  003  福田区
    007  003  宝安区
    008  007  西乡镇
    009  007  龙华镇
    010  007  松岗镇
     
    (所影响的行数为 7 行)
    */
     
    drop table tb
    drop function f_cid
  • 相关阅读:
    glog Windows Visual Studio 2013 编译项目
    Git Tag管理发行版本
    Ubuntu 16.04环境中读取XBOX 360手柄信息
    GCC 中 的pie和fpie选项
    CMakeLists.txt 常用指令说用
    chrome无法访问github.com
    删除前n天的数据
    shell(9)秒转换为时分秒
    Drools规则引擎实践直白总结
    空闲时间研究一个小功能:winform桌面程序如何实现动态更换桌面图标
  • 原文地址:https://www.cnblogs.com/tangxueyang/p/4362775.html
Copyright © 2011-2022 走看看