都是用递归,不过这个递归是循环式的而已,并没有直接的去递归存储过程或函数.

解决方案 »

  1.   

    --一般这会这样处理--分级累计汇总示例--测试数据
    create table 表(dm int,name varchar(10),pid int,xf int,yj int)
    insert 表 select 1,1,0,100,500
    union all select 2,2,1,200,400
    union all select 3,3,2,100,200
    union all select 4,4,3,100,100
    go--计算的存储过程
    create proc p_calc
    as--初始化 yj 字段
    update 表 set yj=-1--分级计算
    update 表 set yj=xf
    from 表 a
    where not exists(
    select 1 from 表 where pid=a.dm)
    while @@rowcount>0
    update 表 set yj=isnull(a.xf,0)+isnull(b.yj,0)
    from 表 a join(
    select pid,yj=sum(yj) from 表
    where yj>=0 group by pid
    )b on a.dm=b.pid
    where a.yj=-1 and not exists(
    select 1 from 表 where pid=a.dm and yj=-1)
    go--调用存储过程进行计算
    exec p_calc--显示计算结果
    select * from 表
    go--删除测试
    drop table 表
    drop proc p_calc/*--测试结果dm          name       pid         xf          yj          
    ----------- ---------- ----------- ----------- ----------- 
    1           1          1           100         500
    2           2          1           200         400
    3           3          2           100         200
    4           4          3           100         100(所影响的行数为 4 行)
    --*/
      

  2.   

    提倡少使用递归,而使用循环