zoukankan      html  css  js  c++  java
  • 树节点查询

    ----------------建表-----------------------
    代码
     1 create table location
     2 (
     3 id bigint,
     4 pid bigint,
     5 name nvarchar(50)
     6 )
     7 go
     8 insert location
     9 select 001,0,'北京市'
    10 union all
    11 select 002,001,'海淀区'
    12 union all
    13 select 003,001,'朝阳区'
    14 union all
    15 select 004,0,'湖南省'
    16 union all
    17 select 005,004,'长沙市'
    18 union all
    19 select 006,004,'株洲市'
    20 union all
    21 select 007,0,'广东省'
    22 union all
    23 select 008,007,'广州市'
    24 union all
    25 select 009,007,'深圳市'
    26 go
    27 select * from location
    28 go
    --查询指定节点及其所有子节点的函数
    代码
     1 create function f_cid(@ID varchar(3)) returns @t_level table(id bigint , level int)
     2 as
     3 begin
     4   declare @level int
     5   set @level = 1
     6   insert into @t_level select @ID , @level
     7   while @@ROWCOUNT > 0
     8   begin
     9     set @level = @level + 1
    10     insert into @t_level select a.id , @level
    11     from location a , @t_Level b
    12     where a.pid = b.id and b.level = @level - 1
    13   end
    14   return
    15 end
    16 go
    17 select * from dbo.f_cid(007as f 
    18 inner join location as t
    19 on f.id=t.id
    20 go
    --采用CTE,比如查询007下所有的子节点
     1 with t
     2 as
     3 (
     4     select id,pid,name from location
     5     where id=007
     6     union all
     7     select c.id,c.pid,c.name from location as c inner join t
     8     on c.pid=t.id
     9 )
    10 select * from t

     --sql08 下有个新特性,我们可以应用 hierarchyid 类型

    代码
     1 CREATE TABLE locationWithHierarchyID
     2 (
     3     [Id] hierarchyid not null primary key,
     4     [Name] nvarchar(50) not null
     5 )
     6 GO
     7 
     8 INSERT INTO locationWithHierarchyID ([Id], [Name] )VALUES
     9     (hierarchyid::GetRoot(), '中国'),
    10     ('/1/''北京市'),
    11     ('/1/1/''海淀区'),
    12     ('/1/2/''朝阳区'),
    13     ('/2/''湖南省'),
    14     ('/2/1/''长沙市'),
    15     ('/2/2/''株洲市'),
    16     ('/3/''广东省'),
    17     ('/3/1/''广州市'),
    18     ('/3/2/''深证市')
    19 GO
    20 select * from locationWithHierarchyID
    21 select Id.ToString() as path,Id.GetLevel() as level, Name  from locationWithHierarchyID
    22 select * from locationWithHierarchyID
    23 where Id.IsDescendantOf('/3/')=1


  • 相关阅读:
    shell 自动登录 上传 下载
    用例设计----PICT&Allpairs
    已有实例 Oracle 下新增实例
    【原创】安卓兼容性测试
    【原创】某版本性能测试
    【原创】Jmeter正则表达式提取json中多个关联值
    【转】四种常见的 POST 提交数据方式
    rfw使用接口库测试--FAIL : UnicodeEncodeError: 'ascii' codec can't encode characters in position
    【原创】Robotframework 简介
    java学习笔记_内存分析
  • 原文地址:https://www.cnblogs.com/youliny/p/1802353.html
Copyright © 2011-2022 走看看