Only inserting a row if it's not already there

后端 未结 6 1015
天涯浪人
天涯浪人 2020-11-22 01:17

I had always used something similar to the following to achieve it:

INSERT INTO TheTable
SELECT
    @primaryKey,
    @value1,
    @value2
WHERE
    NOT EXIST         


        
6条回答
  •  面向向阳花
    2020-11-22 02:09

    I added HOLDLOCK which wasn't present originally. Please disregard the version without this hint.

    As far as I'm concerned, this should be enough:

    INSERT INTO TheTable 
    SELECT 
        @primaryKey, 
        @value1, 
        @value2 
    WHERE 
        NOT EXISTS 
        (SELECT 0
         FROM TheTable WITH (UPDLOCK, HOLDLOCK)
         WHERE PrimaryKey = @primaryKey) 
    

    Also, if you actually want to update a row if it exists and insert if it doesn't, you might find this question useful.

提交回复
热议问题