Only inserting a row if it's not already there

后端 未结 6 918
天涯浪人
天涯浪人 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:16

    You could use MERGE:

    MERGE INTO Target
    USING (VALUES (@primaryKey, @value1, @value2)) Source (key, value1, value2)
    ON Target.key = Source.key
    WHEN MATCHED THEN
        UPDATE SET value1 = Source.value1, value2 = Source.value2
    WHEN NOT MATCHED BY TARGET THEN
        INSERT (Name, ReasonType) VALUES (@primaryKey, @value1, @value2)
    

提交回复
热议问题