How can I do an insert where not exists?

后端 未结 4 579
遥遥无期
遥遥无期 2020-12-15 19:03

I\'d like to combine an insert query with a \"where not exists\" so as not to violate PK constraints. However, syntax such as the following gives me an Incorrect synta

4条回答
  •  [愿得一人]
    2020-12-15 19:39

    INSERT INTO myTable(columns...)
    Select values...
    WHERE NOT EXISTS
       (SELECT *
        FROM myTable
        WHERE pk_part1 = value1,
            AND pk_part2 = value2)
    

    Edit: After reading martins link, If admit, that the best solution is:

    BEGIN TRY
        INSERT INTO myTable(columns...)
        values( values...)
    END TRY
    BEGIN CATCH
        IF ERROR_NUMBER() <> 2627
          RAISERROR etc
    END CATCH;
    

提交回复
热议问题