父 子 值 A B 1 B C 1 B D 2 D E 3 ------------------- A B(1) C(1) D(2) E(3) A有 1 个B,B有 2 个D,D有 3 个E 我想算出A有几个E,几个D ,几个B 怎么写递归,不用递归还有更好的方法吗 我在存储过程里定义游标,然后递归调用该存储过程 实现上面所说的,总说游标已打开或者不存在 怎么解决 ,谢谢
--测试数据
create table 表(父 char(1),子 char(1),值 int)
insert 表 select 'A','B',1
union all select 'B','C',1
union all select 'B','D',2
union all select 'D','E',3
go
--存储过程
create proc p_calc
@id char(1)='A', --要查询的节点
@num int=1 --数量
as
declare @l int
set @l=0
declare @re table(id char(1),level int,num int)
insert @re select @id,@l,@num
while @@rowcount>0
begin
set @l=@l+1
insert @re select a.子,@l,num=b.num*a.值
from 表 a join @re b on a.父=b.id
where b.level=@l-1
end
select id,num=sum(num) from @re group by id
go
--调用查询
exec p_calc
go
--删除测试
drop table 表
drop proc p_calc
/*--测试结果
id num
---- -----------
A 1
B 1
C 1
D 2
E 6
--测试数据
create table 表(父 char(1),子 char(1),值 int)
insert 表 select 'A','B',1
union all select 'B','C',1
union all select 'B','D',2
union all select 'D','E',3
go
--存储过程
create proc p_calc
as
declare @l int
set @l=0
declare @re table(id char(1),level int,[count] int)
insert @re select 子,@l,0
from 表 a
where not exists(select 1 from 表 where 父=a.子)
while @@rowcount>0
begin
set @l=@l+1
insert @re select a.父,@l,[count]=b.[count]+1
from 表 a join @re b on a.子=b.id
where b.level=@l-1
end
select id,[count]=sum([count]) from @re group by id
go
--调用查询
exec p_calc
go
--删除测试
drop table 表
drop proc p_calc
/*--测试结果
id count
---- -----------
A 5
B 3
C 0
D 1
E 0
--测试数据
create table 表(父 char(1),子 char(1),值 int)
insert 表 select 'A','B',1
union all select 'B','C',1
union all select 'B','D',2
union all select 'D','E',3
go
--自定义函数
create function f_id(@id char(1))
returns @re table(id char(1),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.子,@l
from 表 a join @re b on a.父=b.id
where b.level=@l-1
end
return
end
go
--调用,查询A下面的
select * from f_id('A')
go
--删除测试
drop table 表
drop function f_id
/*--测试结果
id level
---- -----------
A 0
B 1
C 2
D 2
E 3
--自定义函数
create function f_id(@id char(1))
returns @re table(id char(1),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.子,@l
from 表 a join @re b on a.父=b.id
where b.level=@l-1
end
return
end
go
--存储过程
create proc p_calc
@id char(1)='A', --要查询的节点
@num int=1 --数量
as
declare @l int
set @l=0
create table #re(id char(1),level int,num int)
insert #re select @id,@l,@num
while @@rowcount>0
begin
set @l=@l+1
insert #re select a.子,@l,num=b.num*a.值
from 表 a join #re b on a.父=b.id
where b.level=@l-1
end
select id,num=sum(num) from #re group by id
go