原文链接地址http://www.cnblogs.com/sweting/archive/2009/06/08/1498483.html

在工作中遇到一个问题,是需要sql递归查询的.不懂,于是到csdn上去问,那里的效率真是非常高,我以前也没在上面问过问题.
 
问题描述:
 
我有一个表结构如下:
id upperid
1     2
3     2
4     1
5     3
具体层次不知道,我想用递归sql语句把所有属于某个upperid的数据,包括它的子树,都读出去,请问应该子怎么写?      
比如说 upperid =2
那么先找到1,3,然后再由1,3找到4,5
使用sql语句实现
 
有两位朋友都给了回复:
fa_ge(鶴嘯九天)
Create table t(id int,upperid int)
insert into t
select 1,     2
union all select 3,     2
union all select 4,     1
union all select 5,     3
select * from t
create function aa(@upperid int)
returns @t table (id int,upperid int,level int)
as
begin
declare @i int
set @i=1
insert into @t
select *,@i from t where upperid=@upperid
while @@rowcount>0
begin
set @i=@i+1
insert into @t
select a.*,@i from t a left join @t b on a.upperid=b.id
where b.level=@i-1
end
return
end
select * from dbo.aa(1)
id          upperid     level       
----------- ----------- ----------- 
4           1           1
(所影响的行数为 1 行)
select * from dbo.aa(2)
id          upperid     level       
----------- ----------- ----------- 
1           2           1
3           2           1
4           1           2
5           3           2
(所影响的行数为 4 行)
这个需要level这个数,否则得不到.
 
hellowork(一两清风)
----创建测试数据
if object_id('tbTest') is not null
drop table tbTest
if object_id('spGetChildren') is not null
drop proc spGetChildren
GO
create table tbTest(id int, upperid int)
insert tbTest
select 1,     2 union all
select 3,     2 union all
select 4,     1 union all
select 5,     3
GO
----创建存储过程
create proc spGetChildren @id int
as
    declare @t table(id int)
    insert @t select id from tbTest where upperid = @id
    while @@rowcount > 0
        insert @t select a.id from tbTest as a inner join @t as b
        on a.upperid = b.id and a.id not in(select id from @t)
    select * from @t
GO
----执行存储过程
declare @upperid int
set @upperid = 2
EXEC spGetChildren @upperid
----清除测试环境
drop proc spGetChildren
drop table tbTest
/*结果
id          
----------- 
1
3
4
5
*/
这个就符合我的要求了.
 
不过我需要的是一个函数,于是改写如下;
create function GetChildren (@id varchar(20))
returns @t table(id varchar(20))
as
begin
    insert @t select wayid from tb where upperwayid = @id
    while @@rowcount > 0
        insert @t select a.wayid from tb as a inner join @t as b
        on a.upperwayid = b.id and a.wayid not in(select id from @t)
   return
end
 
哈哈,真是爽啊.
 
csdn问题地址:
http://community.csdn.net/Expert/topic/5731/5731880.xml?temp=.8160211
 
原来为了解决这个问题,本来想用递归的,在网上看到了下面的资料:

表结构是这样的

部门    上级部门    
A           B
B           C
C           D
A           A
B           B
C           C

求一条SQL语句,根据A查其上级部门,查询结果为
上级部门
B
C
D

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

用函数
create table tb (部门 varchar(20),上级部门 varchar(20))

insert into tb select 'A','B' union all select 'B','C' union all select 'C','D' 
union all select 'A','A' union all select 'B','B' union all select 'C','C'

--select * from tb
create function test_f (@name varchar(20))
returns @ta table(上级部门 varchar(20))
as 
begin 
--select @name=上级部门 from tb where 部门=@name and 部门!=上级部门
while exists(select 1 from tb where 部门=@name and 部门!=上级部门)
begin
insert @ta select 上级部门 from tb where 部门=@name and 部门!=上级部门
select @name=上级部门 from tb where 部门=@name and 部门!=上级部门
end
return
end

select * from dbo.test_f('A')

删除:
drop function test_f
drop table tb

上级部门                 
-------------------- 
B
C
D

(所影响的行数为 3 行)

(转自:http://blog.csdn.net/jackeyabc/archive/2007/03/19/1533775.aspx)

但是可以从部门到上级部门,却不知道怎么修改成为从上级部门到部门.所以最终没有采用

【转】sql递归查询问题的更多相关文章

  1. SQL递归查询实现跟帖盖楼效果

    网易新闻的盖楼乐趣多,某一天也想实现诸如网易新闻跟帖盖楼的功能,无奈技术不佳(基础不牢),网上搜索了资料才发现SQL查询方法有一种叫递归查询,整理如下: 一.查询出 id = 1 的所有子结点 wit ...

  2. SQL递归查询(with as)

    SQL递归查询(with cte as) with cte as(    select Id,Pid,DeptName,0 as lvl from Department    where Id = 2 ...

  3. 关于SQL递归查询在不同数据库中的实现方法

    比如表结构数据如下: Table:Tree ID Name ParentId 1 一级  0 2  二级 1 3  三级 2 4 四级 3 SQL SERVER 2005查询方法: //上查 with ...

  4. SQL递归查询知多少

    最近工作中遇到了一个问题,需要根据保存的流程数据,构建流程图.数据库中保持的流程数据是树形结构的,表结构及数据如下图: 仔细观察表结构,会发现其树形结构的特点: FFIRSTNODE:标记是否为根节点 ...

  5. sql递归查询语句

    sql Bom 递归查询: with t as(select * from Department where id=6union allselect a.* from Department a,t w ...

  6. SQL递归查询实现组织机构树

    系统用到的组织机构树,要实现对当前节点以及其子节点的查询,数据库SQL要用到递归查询,这也是我第一次接触SQL的递归查询. 先说一下什么是递归查询,简单说来是将一个树状结构存储在一张表里,比如一个表中 ...

  7. SQL 递归查询,意淫CTE递归的执行步骤

    今天用到了sql的递归查询.递归查询是CTE语句with xx as(....)实现的. 假如表Category数据如下. 我们想查找机枪这个子分类极其层次关系(通过子节点,查询所有层级节点).以下是 ...

  8. easyUI 的tree 修改节点,sql递归查询

    1.easyUI 的tree 修改节点: 我需要:切换语言状态,英文下, 修改根节点文本,显示英文. 操作位置:在tree的显示 $('#tree').tree(),onLoadSuccess事件方法 ...

  9. SQL递归查询(with cte as)

    with cte as ( select Id,Pid,DeptName,0 as lvl from Department where Id = 2 union all select d.Id,d.P ...

随机推荐

  1. 自己在完第一遍STL和Directx 9.0 游戏开发编程基础书后的体会

    如果一本书看一遍就能看懂,说明书对自己相对容易,没有必要在去看第二遍,但是对于大多数书籍,都有自己陌生的知识,看完一遍无法理解的地方,说明就是自己知识点最薄弱的,最需要去理解的地方,一旦自己理解了这些 ...

  2. Oracle Linux下数据库操作的相关问题

    1.su - oracle 切换到oracle用户 lsnrctl status 查看数据库监听状态 lsnrctl start 打开数据库监听 2.Connected to an idle inst ...

  3. if __name__ == '__main__的理解

    模块之间引用不能循环成环,圆圈   模块的收搜   !!!把模块当作脚本执行 什么叫模块:py文件,如果一个py文件被导入了,他就是一个模块, 模块没有具体的调用过程 但是能对外提供功能   什么叫脚 ...

  4. POJ 3169.Layout 最短路

    Layout Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 11612   Accepted: 5550 Descripti ...

  5. JVM运行时数据区域解析

         Java与C++之间有一堵由内存动态分配和垃圾收集技术所围成的高墙,墙外面的人想进去,墙里面的人想出来.      Java虚拟机在执行Java程序的过程中会把它所管理的内存划分为若干个不同 ...

  6. wmi uuid

    [转]https://www.cnblogs.com/-sylar/p/8376621.html 1. 开始-运行-输入:wbemtest 回车2. 单击"连接", 输入:root ...

  7. python线程池

    https://blog.csdn.net/qq_33961117/article/details/82587873#!/usr/bin/python # -*- coding: utf- -*- f ...

  8. mapreduce的输入格式 --- InputFormat

    InputFormat 接口决定了mapreduce如何切分输入文件. InputFormat 由getspilit和createRecordReader组成,getspilit主要是标记分片的初始位 ...

  9. MVVM Light 笔记 - snippet

    RelayCommand有8个,看似很多,其实就是几个变化的组合: 1.是否Generic 2. 执行是使用lambda表达式还是method 3.是否有CanExecute 这些都在源代码Snipp ...

  10. Java第3章笔记

    if基本语法: if(条件){// 表达式   // 代码块   } eg:    int a = 10;    if(a > 1){  System.out.println("内容& ...