Danger of using 'IF EXISTS… UPDATE .. ELSE .. INSERT' and what is the alternative?

后端 未结 4 1246
既然无缘
既然无缘 2021-01-17 03:42

This question is related with Occasionally Getting SqlException: Timeout expired. Actually, I am using IF EXISTS... UPDATE .. ELSE .. INSERT heavily in my app.

4条回答
  •  醉话见心
    2021-01-17 04:01

    Merge, is in the first case created to compare 2 tables, so if that is the case you could use merge.

    Take a look at the following, which is also another option.

    In this case unfortunately you have the possibility of getting a problem with concurrency.

    --Just update a row 
    UPDATE Table1 SET (...) WHERE Column1='SomeValue'
       -- If 0 rows are updated ...
      IF @@ROWCOUNT=0
    --Insert Row
    INSERT INTO Table1 VALUES (...)
    

    In this blog its explained more.

    Additionally this interesting blog is about concurrency.

提交回复
热议问题