Sql Server 2005 - Insert if not exists

后端 未结 2 1205
挽巷
挽巷 2021-01-18 03:31

There is lots of information in the internet regarding this common \"problem\".

Solutions like:

IF NOT EXISTS() BEGIN INSERT INTO (...) END
<         


        
相关标签:
2条回答
  • 2021-01-18 04:03

    To answer the updated question repeatable read would still not be sufficient.

    It is holdlock / serializable level that you would need.

    You are trying to prevent phantoms (where on the first read no rows met the criteria so the NOT EXISTS returns true but subsequently a concurrent transaction inserts a row meeting it)

    0 讨论(0)
  • 2021-01-18 04:10

    With TRY/CATCH you can avoid the extra read

    BEGIN TRY
       INSERT etc
    END TRY
    BEGIN CATCH
        IF ERROR_NUMBER() <> 2627
          RAISERROR etc
    END CATCH
    
    • A NOT EXISTS will read the table, whether in the IF or WHERE
    • The INSERT requires a read to check uniqueness

    If you can discard duplicates, this is a highly scalable technique

    Links:

    • See my answers here: Only inserting a row if it's not already there and SQL Server 2008: INSERT if not exits, maintain unique column
    • If you requires UPDATEs too: Which is the best choice in delete-insert vs if-update else-insert?
    0 讨论(0)
提交回复
热议问题