How to Ignore “Duplicate Key” error in T-SQL (SQL Server)

后端 未结 12 669
故里飘歌
故里飘歌 2020-12-02 18:12

I have a transaction that contains multiple SQL Statements (INSERT, UPDATE and/or DELETES). When executing, I want to ignore Duplicate Error statements and continue onto the

12条回答
  •  我在风中等你
    2020-12-02 19:05

    INSERT INTO KeyedTable(KeyField, Otherfield)
    SELECT n.* FROM 
        (SELECT 'PossibleDupeLiteral' AS KeyField, 'OtherfieldValue' AS Otherfield
         UNION ALL
         SELECT 'PossibleDupeLiteral', 'OtherfieldValue2'
        )
    LEFT JOIN KeyedTable k
        ON k.KeyField=n.KeyField
    WHERE k.KeyField IS NULL
    

    This tells the Server to look for the same data (hopefully the same speedy way it does to check for duplicate keys) and insert nothing if it finds it.

    I like the IGNORE_DUP_KEY solution too, but then anyone who relies on errors to catch problems will be mystified when the server silently ignores their dupe-key errors.

    The reason I choose this over Philip Kelley's solution is that you can provide several rows of data and only have the missing ones actually get in:

提交回复
热议问题