要求:插入前判断该数据是否已经存在,如果存在则更新sl字段,不存在则添加新数据
测试数据
create table #t
(
ys int,
sl int
)
insert #t values(0,12)
insert #t values(1,12)
insert #t values(2,12)
ys字段值为0,1,2,3.现在每插入一条新数据时,都需要判断ys字段值是否已经存在。
存储过程实现

解决方案 »

  1.   


    需要用变量declare @ys int ,@sl intif exists(select 1 from #t where ys=@ys)
    update #t set sl=@sl
    where ys=@ysinsert into #t select @ys,@sl
      

  2.   

    需要用变量 declare @ys int ,@sl int if exists(select 1 from #t where ys=@ys) 
    update #t set sl=@sl 
    where ys=@ys insert into #t select @ys,@sl
      

  3.   

    在存储过程中用 when  字段 case 条件1 then  XXX 
                            case 条件2 then  XXX 
                            else XXX
      

  4.   

    create proc p_test
     @ys int ,@sl int
    as
    if exists(select 1 from tbname where ys=@ys)
    update tbname set sl=@sl where ys=@ys
    else
    insert into tbname select @ys,@sl