原文链接地址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. Error starting daemon: error initializing graphdriver: driver not supported

    Error starting daemon: error initializing graphdriver: driver not supported systemctl stop docker rm ...

  2. lodash 中常用的方法

    odash是js集Array/Object/String/Function的Util于一身. lodash打包了Array/Object/String/Function里一些Api,好处是连ES6的也 ...

  3. 使用hMailServer搭建邮件服务器

    本文没有什么高深的技术内容,只是使用hMailServer,介绍搭建邮件服务器的全过程,供参考. 一.安装邮件服务器组件 打开软件,点下一步 选择存储数据的数据库,这里有两种选择, 一种是使用嵌入型数 ...

  4. Predict the Winner LT486

    Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from eith ...

  5. IOS 小新兵

    2017-07-02 lipo -info BaiduOAuthSDK.a  查看a文件支持的架构 第一个坎: 报错:  未找到模块baiduLogin对应的类BaiduLoginModule.若是自 ...

  6. linux代码常用查询!!!!!!!!!!!!

    字符串: echo "a b c d e f"|cut -d ' ' -f1            输出a echo "a b c d e f"|cut -d  ...

  7. fastcgi 环境变量例子

    例如请求的url http://172.28.250.184:8099/aa.php?var=ccccc&value=bbbbbb 前两个字节分别代表  变量名长度  和 变量值长度. 0x0 ...

  8. GOIP connects with Elastix through “config by line”

    GOIP connects with Elastix through “config by line” By grace Liu on May 17, 2013 in Elastix, Gateway ...

  9. 我们用整整三年时间,建成了一套软件:用户定制系统(UD)

    这是我们花了三年时间,完成了一套软件--用户定制系统(UD) 主要功能就是集中在下面这个界面了 (自己生成自己哦) ============================= 更多详情,请您访问:我们 ...

  10. spring 学习 二 IOC/DI

    中文名称:控制反转 英文名称:( Inversion of Control ) 1 控制反转作用: 一般在编写java程序时,需要程序员自己创建对象的实例,例如 A a=new A();语句,就是程序 ...