余额    赠送余额
id      bl     bl_t
1 340 15
2 500 20 上表是一余额表,如果客人(ID1)买了一个东西20元。那么他的余额应该是:
id      bl     bl_t
1 335 0
自己水平实在有限,解决不了又来求助了。请问这样应该怎么实现?谢谢

解决方案 »

  1.   

    declare @money int
    set @money=20
    select id,b1=b1+b1_t-@money,b1_t=case when b1_t<=@money then 0 else b1_t-@money  end from tb
      

  2.   

    这样好象有问题,如果他买的这东西是5元您的结果是
    bl    bl_t
    350    10
    正确的应该是
    bl    bl_t
    340    10
      

  3.   


    if object_id('tb','U') is not null
       drop table tb
    go
    create table tb
    (
     id int,
     b1 int,
     b1_t int
    )
    go
    insert into tb
    select 1,340,15 union all
    select 2,500,20
    go
    update tb set b1_t=case when b1_t-20<0 then 0 else b1_t-20 end,
                  b1=case when b1_t-20<0 then b1-(20-b1_t) else b1_t end 
    where id=1
    /*
    id          b1          b1_t
    ----------- ----------- -----------
    1           335         0
    2           500         20(2 行受影响)*/
      

  4.   


    --修改一下,楼主可以把@i变量的值换成5或20
    if object_id('tb','U') is not null
       drop table tb
    go
    create table tb
    (
     id int,
     b1 int,
     b1_t int
    )
    go
    insert into tb
    select 1,340,15 union all
    select 2,500,20
    go
    declare @i int
    set @i=20
    update tb set b1_t=case when b1_t-@i<0 then 0 else b1_t-@i end,
                  b1=case when b1_t-@i<0 then b1-(@i-b1_t) else b1 end 
    where id=1select * from tb
    /*
    id          b1          b1_t
    ----------- ----------- -----------
    1           335         0
    2           500         20(2 行受影响)
    */
      

  5.   


    create  procedure  updatetb
    @v int
    as
    update tb set b1_t=case when b1_t-@v<0 then 0 else b1_t-@v end,
                  b1=case when b1_t-@v<0 then b1-(@v-b1_t) else b1 end 
    where id=1
    go对,4楼改过之后测试对了。谢谢。哈哈。你厉害
      

  6.   

    感谢两位高手。我代表CSDN向你们致以。