alter table  M add  余额 intdeclare    @rem   int 
declare    @aid   int
declare    @borrow int
declare    @lend    int
declare  mycursor cursor for
        select aid, 贷发生,借发生 from M
select @rem=0
open mycursorfetch mycursor into 
     @aid, @lend,@borrow
while(@@fetch_status=0)
   begin select  @rem=@rem+@lend-@borrow
         update M set   余额=@rem  where aid=@aid
         fetch next from mycursor into @aid, @lend,@borrow
   end
close mycursor
deallocate mycursor

解决方案 »

  1.   

    create table M(aid int ,贷发生 int ,借发生 int )
    insert M select  1,200,100
    union all select 2,400,200
    union all select 3,200,0
    union all select 4,0,100alter table  M add  余额 int
    declare    @rem   int 
    declare    @aid   int
    declare    @borrow int
    declare    @lend    int
    declare  mycursor cursor for
            select aid, 贷发生,借发生 from M
    select @rem=0
    open mycursorfetch mycursor into 
         @aid, @lend,@borrow
    while(@@fetch_status=0)
       begin select  @rem=@rem+@lend-@borrow
             update M set   余额=@rem  where aid=@aid
             fetch next from mycursor into @aid, @lend,@borrow
       end
    close mycursor
    deallocate mycursor--result
    1 200 100 100
    2 400 100 300
    3 200 0 500
    4 0 100 400
      

  2.   

    select a.*,(select sum(isnull(贷发生,0)-isnull(借发生,0)) from table where table.id<=a.id  )as 余额 
    from table a
      

  3.   

    同意
    zjmym(缘木)的做法