表A字段:
客户编码:CustID  (字符)            [主键]
商品编码:ProID   (字符)            [主键]
销售日期:saleDate(日期)            [主键]
重量:    saleTotalweight(decimal,4位小数)    
求一存储过程传入该字段四个参数,
参数顺序为字段顺序(custID,ProID,saleDate,saleTotalweight)返回值:
累加后的重量要求:
1.如已存在该条纪录,重量累加:
select saleTotalweight from A where CustID=@CustID and proID=@proID and saleDate = @saleDateif exist() -> 原有重量+传入重量
if 没有前三个字段(主键)对应纪录,则insert()一条。
insert()时注意,如果是负数,重量为零,正数为传入值。2.传入的重量可能为负数(冲减)
也是传入重量与原有重量累加,如累加值为负,由update这纪录的重量为零。

解决方案 »

  1.   

    create proc procname
    @custid varchar(10),
    @proid varchar(10),
    @saledate datetime,
    @saletotalweight decimal(12,4),
    @ret decimal(12,4) output
    as 
    declare @old decimal(12,4)
    select @old = saleTotalweight from A where CustID=@CustID and proID=@proID and saleDate = @saleDate 
    if @@rowcount > 1 
    begin
       set @ret = @old + @saletotalweight 
       if @ret < 0 
          update a set saleTotalweight = 0
          where CustID=@CustID and proID=@proID and saleDate = @saleDate
    end 
    else
       insert a select @custid ,@proid ,@saledate,case when @saletotalweight > 0 then @saletotalweight else  0 endgo
      

  2.   

    if exists(select 1 from A   where   CustID=@CustID   and   proID=@proID   and   saleDate   =   @saleDate )
    update a
    set saleTotalweight=saleTotalweight+@saleTotalweight
    where   CustID=@CustID   and   proID=@proID   and   saleDate   =   @saleDate 
    else
    insert a values(@CustID,@proID,@saleDate,@saleTotalweight)