请教一sql写法(我实现的方法效率太慢)

BraveXu 2005-04-03 05:34:42
表的架构如下

架构类别架构id 架构描述 父架构类别 父架构id
DTb 0 生产本部 1 1 NULL NULL
Kb 00 生产管理课 1 1 NULL NULL
Kb 01 生产技术课 1 1 NULL NULL
Kb 31 混练课 1 1 3 sDTb
Kb 51 延压课 1 1 5 sDTb
Kb 52 押出课 1 1 5 sDTb
Kb 53 裁断课 1 1 5 sDTb
Kb 61 成一课 1 1 000035 6 sDTb
Kb 62 成二课 1 1 6 sDTb
Kb 63 成三课 1 1 6 sDTb
Kb 71 加硫一课 1 1 7 sDTb
Kb 72 加硫二课 1 1 7 sDTb
Kb 73 测定课 1 1 7 sDTb
sDTb 3 混练部 1 1 0 DTb
sDTb 5 押延部 1 1 0 DTb
sDTb 6 成型部 1 1 0 DTb
sDTb 7 加硫部 1 1 0 DTb

员工表
工号 架构类别 架构id
000011 DTb 0
000023 Kb 63
......

现想用一SQL语句查处一员工所有下属员工信息(即子架构下员工,递推到结束),如000011

请高人指点......
...全文
168 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
Navywang917 2005-04-07
  • 打赏
  • 举报
回复
接分
zierben 2005-04-07
  • 打赏
  • 举报
回复
没有看明白。。。
BraveXu 2005-04-07
  • 打赏
  • 举报
回复
我自己琢磨着写function解决了,不过为了信誉,还是要给分的,我那可怜的80分阿
BraveXu 2005-04-03
  • 打赏
  • 举报
回复
to 631799(杭州工人) ( )
我觉得你可能没有真正明白我的意思
架构类别 & 架构id 是联合主键,如DTb & 0 标示部门别 代号为0
十分感谢你的方案,可是遗憾的是解决不了我的问题。
xluzhong 2005-04-03
  • 打赏
  • 举报
回复
---------关于树的例子,希望能给你帮助。
create table a( UserID int, UserName nvarchar(10), Ratio int, Amount int, FatherID int)
insert into a
select 1, N'田方', 12, 200, 0 union all
select 2, N'张三', 8, 100, 1 union all
select 3, N'李四', 12, 200, 1 union all
select 4, N'王五', 6, 130, 2 union all
select 5, N'杨六', 9, 200, 3 union all
select 6, N'陈七', 4, 190, 2
go

create function f_cid(
@id int
)returns @re table(userid int,[level] int)
as
begin
declare @l int
set @l=0
insert @re select @id,@l
while @@rowcount>0
begin
set @l=@l+1
insert @re select a.userid,@l
from a,@re b
where a.fatherid=b.userid and b.[level]=@l-1
end
return
end
go


select a.*,层次=b.[level],amount*ratio/100 as fee from a,f_cid(2)b
where a.userid=b.userid
-----------------
select sum(fee)
from(
select a.*,层次=b.[level],amount*ratio/100 as fee from a,f_cid(2)b
where a.userid=b.userid
)t
go

drop function f_cid
drop table a

skeeterLa 2005-04-03
  • 打赏
  • 举报
回复
up
631799 2005-04-03
  • 打赏
  • 举报
回复
create function f_getchildid(@id int)
returns @re table(id int)
as
begin
insert into @re select 架构id from 表 where 父架构id=@id -- 这里改一改
while @@rowcount>0
insert into @re select a.架构id
from 表 a inner join @re b on a.父架构id=b.架构id
where a.架构id not in(select 架构id from @re)
return
end
go
631799 2005-04-03
  • 打赏
  • 举报
回复
create function f_getchildid(@id int)
returns @re table(id int)
as
begin
insert into @re select 架构id from 表 where 父架构id=@架构id
while @@rowcount>0
insert into @re select a.架构id
from 表 a inner join @re b on a.父架构id=b.架构id
where a.架构id not in(select 架构id from @re)
return
end
go


--调用示例,显示1的所有子.
select a.* from 表 a inner join dbo.f_getchildid(1) b on a.架构id=b.架构id

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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