zoukankan      html  css  js  c++  java
  • 不用ms sql server 公共表达式CTE递归时的循环算法

    受到这个地址的启发

    http://blog.chinaunix.net/space.php?uid=660282&do=blog&cuid=369590

    要根据第一个查询条件,查出所有parent id=id的集,也就是树状目录递归查询,查出所有的分叶

    CREATE PROC spGetChildren (@id int)    
    as
    declare @t table(id int,node_name nchar(10),parent_id int) ----声明一个临时表
    insert @t select * from t_tree where id = @id ----查找第一个记录,就是顶层节点
    while @@rowcount > 0 ----这个全局变量代表受影响的行,直到没有记录,会一直查下去
    insert @t select a.* from t_tree as a inner join @t as b
    on a.parent_id = b.id and a.id not in(select id from @t)
    select * from @t
    GO
    ----执行存储过程
    declare @parent_id int
    set @parent_id = 1
    EXEC spGetChildren @parent_id
    ----清除测试环境
    --
    drop proc spGetChildren

    =============

    下面是纯粹的sql语句,不带存储过程

    declare @t table(id int,node_name nchar(10),parent_id int)
    insert @t select * from t_tree where id = 1 -----定位点,定位第一个节点
    while @@rowcount > 0
    insert @t select a.* from t_tree as a inner join @t as b
    on a.parent_id = b.id and a.id not in(select id from @t)
    select * from @t

    on和where类似,不过它是T-SQL独有的,另外很多sql命令支持缩写,比如insert into 直接写成insert

    1、 on条件是在生成临时表时使用的条件,它不管on中的条件是否为真,都会返回左边表中的记录。

    2、where条件是在临时表生成好后,再对临时表进行过滤的条件。这时已经没有left join的含义(必须返回左边表的记录)了,条件不为真的就全部过滤掉。

  • 相关阅读:
    struts总结
    struts的MVC详细实现
    struts的由来
    Hibernate的搭建及使用
    Hibernate简介
    泛型
    eclipse手动添加源码
    beanUtils操作bean的属性
    ref:JAVA之Forward和Redirect的区别
    ref:下一个项目为什么要用 SLF4J
  • 原文地址:https://www.cnblogs.com/abcbuzhiming/p/2180663.html
Copyright © 2011-2022 走看看