若我在表tb1找到满足条件时,我用UPDATE修改这行记录,否则用INSERT新增一行新记录。究竟用TOP 1, 还是用count() ,或其它?select top 1 from tb1 where 条件(这里如何写?)
if ....找到,则返回值(这里如何写?)
    UPDATE TB1 ......
else
    INSERT ......
    

解决方案 »

  1.   

    找到就修改,用不着top:
    update tb1 set col=newvalue where 条件
      

  2.   

    if exists(select 1 from tb1 where 条件) -- 不存在
       insert into ...
    else --存在
       update ...
      

  3.   

    if exists(select 1 from ....where ....)
    update..
    else
    insert...
      

  4.   


    --或者
    if exists(select top 1 from tb1 where 条件(这里如何写?))
      UPDATE TB1 ......
    else
      INSERT ......
      

  5.   

    if exists(select 1 from TB where ...)
    begin
      update.....
    end
    else
    begin
     insert ....
    end
      

  6.   

    搞反了.应该是:
    if not exists(select 1 from tb1 where 条件) -- 不存在
      insert into ...
    else --存在
      update ...
      

  7.   

    找到就修改,否则就插入,直接用两句语句:
    假设是从另一个表中查到的数据集:
    先更新:
    update a set col=b.col from tb1 a --这是被修改表
    inner join tb2 b --这是提供数据的表
    on a.id=b.id
    再插入
    insert into tb1
    select * from tb2 where not exists(select 1 from tb1 where id=tb2.id)