请教一sql写法(我实现的方法效率太慢)
表的架构如下
架构类别架构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
请高人指点......
问题点数:80、回复次数:8Top
1 楼631799(杭州工人)回复于 2005-04-03 17:58:22 得分 40
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.架构idTop
2 楼631799(杭州工人)回复于 2005-04-03 18:13:33 得分 0
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
goTop
3 楼skeeterLa(英俊的大米虫)回复于 2005-04-03 18:39:14 得分 5
upTop
4 楼xluzhong(Ralph)回复于 2005-04-03 19:29:11 得分 25
---------关于树的例子,希望能给你帮助。
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
Top
5 楼BraveXu(鱼之乐)回复于 2005-04-03 19:38:02 得分 0
to 631799(杭州工人) ( )
我觉得你可能没有真正明白我的意思
架构类别 & 架构id 是联合主键,如DTb & 0 标示部门别 代号为0
十分感谢你的方案,可是遗憾的是解决不了我的问题。
Top
6 楼BraveXu(鱼之乐)回复于 2005-04-07 15:38:04 得分 0
我自己琢磨着写function解决了,不过为了信誉,还是要给分的,我那可怜的80分阿Top
7 楼coollangzi(风)回复于 2005-04-07 16:31:03 得分 5
没有看明白。。。Top
8 楼Navywang917(狼泪)回复于 2005-04-07 16:39:31 得分 5
接分Top




