SQL Server 2005 implementation of MySQL REPLACE INTO?

后端 未结 4 1329
星月不相逢
星月不相逢 2020-12-04 14:57

MySQL has this incredibly useful yet proprietary REPLACE INTO SQL Command.

Can this easily be emulated in SQL Server 2005?

Starting a new Trans

4条回答
  •  春和景丽
    2020-12-04 15:37

    I wrote a blog post about this issue.

    The bottom line is that if you want cheap updates and want to be safe for concurrent usage, try:

    update t
    set hitCount = hitCount + 1
    where pk = @id
    
    if @@rowcount < 1 
    begin 
       begin tran
          update t with (serializable)
          set hitCount = hitCount + 1
          where pk = @id
          if @@rowcount = 0
          begin
             insert t (pk, hitCount)
             values (@id,1)
          end
       commit tran
    end
    

    This way you have 1 operation for updates and a max of 3 operations for inserts. So, if you are generally updating, this is a safe cheap option.

    I would also be very careful not to use anything that is unsafe for concurrent usage. It's really easy to get primary key violations or duplicate rows in production.

提交回复
热议问题