如何在sql语句中实现递归查询?

文东win 2004-04-08 04:40:15
我有两张表:
人员表man:
mancode //人员编码
manname //人员姓名
deptcode //所属部门编码

部门表dept:
deptcode //部门编码
deptname //部门名称
parentdeptcode //上级部门编码

在dept表中通过parentdeptcode(上级部门编码)实现单位的所属关系和层次划分,
假设有部门的层次如下:

部门a
部门a1
部门a11
部门a12
部门a13
部门a2
部门a21
部门a211
部门a22
部门a23
部门b


我现在想查询部门a中的所有人员如何在一个sql语句中查出来?
...全文
92 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
blucecat 2004-04-08
  • 打赏
  • 举报
回复
你的部门编码最好有规律些,这样就可以一条语句搞定(象gg,monkey那样),否则就比较麻烦(象邹健那样)
caiyunxia 2004-04-08
  • 打赏
  • 举报
回复
select * from man where left(deptcode,1)='a'
LoveSQL 2004-04-08
  • 打赏
  • 举报
回复
直接一句就可以找到所以a部门的人拉

select * from man where deptcode like 'a%'
zjcxc 2004-04-08
  • 打赏
  • 举报
回复
一条语句搞不写.

写个自定义函数.

以后查询时倒是一条语句就可以了.
zjcxc 2004-04-08
  • 打赏
  • 举报
回复
--创建一个处理函数
create function f_child(@deptname varchar(10))
returns @re table(deptcode int,level int)
as
begin
declare @l int
set @l=0
insert @re select deptcode,@l from dept where deptname=@deptname
while @@rowcount>0
begin
set @l=@l+1
insert @re select a.deptcode,@l
from dept a join @re b on a.parentdeptcode=b.deptcode
where b.level=@l-1
end
return
end
go

--调用实现楼主要的查询
select a.* from man a
join f_child('部门a') b on a.deptcode=b.deptcode
zljblue 2004-04-08
  • 打赏
  • 举报
回复
select * from man where deptcode in
(select deptcode from dept where deptcode like %a%)
progress99 2004-04-08
  • 打赏
  • 举报
回复
請參考:
树形数据的处理
http://expert.csdn.net/Expert/topic/2285/2285830.xml?temp=.5049707

22,207

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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