create proc usp_addnew
 @whbn int,
 @cbh char(10),
 @sl float(8)
as
declare @rc int
select @rc=0
begin
if not exists (select * from yourtable where whbh=@whbn and cbh=@cbh)
insert into youtable values (@whbn,@cbh,@sl)
else
update yourtable set sl=@sl where whbh=@whbn and cbh=@cbh
select @rc=@@error
if @rc<>0
begin
select @rc=-1
return @rc
endend

解决方案 »

  1.   

    select @rc=@@error
    if @rc<>0
    begin
    select @rc=-1
    return @rc
    end这是什么意思。是不是表示没有错误。
      

  2.   

    if @rc<>0:表示有错误。
      

  3.   

    leimin(黄山光明顶)的写法有一个小错误 ,我给更正一下:
     
      create proc usp_addnew
     @whbn int,
     @cbh char(10),
     @sl float(8)
    as
    declare @rc int
    select @rc=0if not exists (select * from yourtable where whbh=@whbn and cbh=@cbh)
    insert into youtable values (@whbn,@cbh,@sl)
    else
    update yourtable 
             set sl=sl+@sl 
             where whbh=@whbn and cbh=@cbhselect @rc=@@error
    if @rc<>0
    select @rc=-1
    return @rcgo呵呵,版主也要上班,不一定在线。而且tj_dns(愉快的登山者) 给你解释了!
      
     
      

  4.   

    上面的大版主已经答复你了。我再提供另外一种方法,版主不会24小时在呀create table ytfwh(whbh int,cbh char(10),sl float(8))
    create unique index i_u_ytfwh on ytfwh(whbh,cbh)
    ---------------------------------------------------------------
    create proc MyProc   --这是你要的存储过程
    @whbh int,
    @cbh char(10),
    @sl float(10)
    as
    update ytfwh
    set sl = sl + @sl
    where whbh = @whbh and cbh = @cbhif @@rowcount=0  --如果修改的记录数为零,则插入
    insert into ytfwh(whbh,cbh,sl)
    values(@whbh,@cbh,@sl)
    -----------------------------------------------------------------
    go--以下是执行结果:
    exec myproc 1,'a',3.25
    exec myproc 1,'b',5
    exec myproc 1,'a',6select * from ytfwh--1 a          9.25
    --1 b          5.0--建议,如果每次只插入一条记录,更好的办法是将这个
    --控制建在ytfwh表的触发器里。
    ----------------------------------------------------------------
    create trigger mytrig on ytfwh instead of insert as
    update ytfwh
    set sl = ytfwh.sl + b.sl
    from inserted b
    where ytfwh.whbh = b.whbh and ytfwh.cbh = b.cbhif @@rowcount=0  --如果修改的记录数为零,则插入
    insert into ytfwh(whbh,cbh,sl)
    select whbh,cbh,sl 
    from inserted
    -----------------------------------------------------------------
    --然后直接往该表插入数据就可以了。
      

  5.   

    我是一次只插入一条记录。b表没有whbh这个字段呀, 是用户在combobox动态选择得到的 whbh.再传递过来的。你在触发器里怎么得到这个参数
      

  6.   

    前端工具是什么?
    用触发器不用参数呀,你直接在前端工具写insert语句也可以。如果不行就用存储过程吧。