Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

sql-server

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 next statement. What's the best way of doing that?

like image 379
Kingamoon Avatar asked Jul 16 '09 17:07

Kingamoon


People also ask

How do you prevent repeated values in SQL?

If you want the query to return only unique rows, use the keyword DISTINCT after SELECT . DISTINCT can be used to fetch unique rows from one or more columns. You need to list the columns after the DISTINCT keyword.

What is duplicate key error?

A duplicate key error means that there is already an instance in the table that has the same key field as the instance to be inserted. If duplicate key errors occur, the status of the file will change to Transfer of Data to Staging Tables Failed.

What is duplicate key error in SQL?

You are inserting the records from A back into itself, thus you are attempting to create a new row using a Primary Key value that is already being used. This leads to the error message that you see.


1 Answers

I think you are looking for the IGNORE_DUP_KEY option on your index. Have a look at IGNORE_DUP_KEY ON option documented at http://msdn.microsoft.com/en-us/library/ms186869.aspx which causes duplicate insertion attempts to produce a warning instead of an error.

like image 73
Emmanuel Avatar answered Oct 04 '22 13:10

Emmanuel