您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

求SQL语句递归的算法

2024/4/27 19:22:09发布13次查看
表结构是这样的 部门 上级部门 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 行)

该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product