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

后端 未结 12 660
故里飘歌
故里飘歌 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:04

    Expanding on your comment to SquareCog's reply, you could do:

    INSERT INTO X VALUES(Y,Z)    WHERE Y  NOT IN (SELECT Y FROM X)
    INSERT INTO X2 VALUES(Y2,Z2) WHERE Y2 NOT IN (SELECT Y FROM X2)
    INSERT INTO X3 VALUES(Y3,Z3) WHERE Y3 NOT IN (SELECT Y FROM X3)
    

    Here, I assume that column Y is present in all three tables. Note that performance will be poor if the tables are not indexed on Y.

    Oh yeah, Y has a unique constraint on it--so they're indexed, and this should perform optimally.

提交回复
热议问题