求SQL语句一条

yuanqi007 2006-12-17 10:36:32
表结构是这样的

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

求一条SQL语句,根据A查其上级部门,查询结果为
上级部门
B
C
D
...全文
207 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
中国风 2006-12-17
  • 打赏
  • 举报
回复
用函数
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 行)


mschen 2006-12-17
  • 打赏
  • 举报
回复
使用SQL SERVER 2005的CTE应该可以实现.

with department
as
(
select * from 表
where 部门='A'
union all
select
from 表 a join department b
on a.部门=b.上级部门
)
select * from department
Go
marco08 2006-12-17
  • 打赏
  • 举报
回复
后三行数据如何理解?
sgucxc0 2006-12-17
  • 打赏
  • 举报
回复
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
/*
A B
B C
C D
A A
B B
C C
*/

create proc ShowParentId
@subid varchar(20)
as
begin
declare @pid varchar(20)
create table #temp (pid varchar(20) primary key)
select @pid=isnull(上级部门,'0') from tb where 部门=@subid and 上级部门<>@subid
while @@rowcount<>0
begin
insert into #temp select @pid
select @pid=isnull(上级部门,'0') from tb where 部门=@pid and 上级部门<>@pid
end
select pid from #temp
drop table #temp
end
go

exec ShowParentId 'A'
/*结果
B
C
D
*/

drop proc ShowParentId
drop table tb
jackeyabc 2006-12-17
  • 打赏
  • 举报
回复
对,递归
dawugui 2006-12-17
  • 打赏
  • 举报
回复
应该是个递归的算法.
点点星灯 2006-12-17
  • 打赏
  • 举报
回复
http://blog.csdn.net/zjcxc/archive/2003/12/29/20073.aspx
--第6个
peisong 2006-12-17
  • 打赏
  • 举报
回复
A A
B B
C C
如何理解?

34,593

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧