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


  • 相关阅读:
    AngularJS---核心特性
    前后端分离原理
    吴军 见识 读后感
    CSS 颜色名称和CSS 颜色十六进制值
    springmvc+jsp引用本地图片文件
    Eclipse 构建Maven项目--普通web项目 复制另外一个项目的配置文件导致的问题
    html input type=date 赋值问题 必须yyyy-mm-dd格式
    解决eclipse中运行web项目时弹出的"Port 8080 required by Tomcat 9.0 Server at localhost is already in use...
    解决 Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)
    SpringMVC HelloWorld实例开发及部署
  • 原文地址:https://www.cnblogs.com/youliny/p/1802353.html
Copyright © 2011-2022 走看看