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


  • 相关阅读:
    elasticsearch配置文件详解
    《禅的故事》--易中天
    《爱你就像爱生命》--王小波
    Adaboost算法及其代码实现
    HOG特征原理及代码实现
    SMO算法--SVM(3)
    非线性支持向量机SVM
    核方法-核技巧-核函数
    线性可分支持向量机与软间隔最大化--SVM(2)
    拉格朗日乘子(Lagrange multify)和KKT条件
  • 原文地址:https://www.cnblogs.com/youliny/p/1802353.html
Copyright © 2011-2022 走看看