求SQL语句递归的算法

WBOY
發布: 2016-06-07 17:37:12
原創
940 人瀏覽過

表结构是这样的 部门 上级部门 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

表结构是这样的

部门    上级部门    
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 行)

 

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!