Pregunta

Is there a way to prevent sql from throwing an error when I try to save a record that already exists. I've got a composite key table for a many-to-many relationship that has only the two values, when I update a model from my application, it tries to save all records, the records that already exist throw an error Cannot insert duplicate key is there a way of having the database ignore these, or do I have to handle it in the application?

¿Fue útil?

Solución

you are calling an INSERT and trying to add duplicated keys. This error is by design, and essential. The DB is throwing an exception for an exceptional and erroneous condition.

If you are, instead, trying to perform an "upsert" you may need to use a stored procedure or use the MERGE syntax.

If, instead, you don't want to UPDATE but to just ignore rows already in the table, then you need to simply add an exception to your INSERT statement... such as

....
WHERE 
    table.Key <> interting.key

Otros consejos

Try something like this with your insert statement.

insert into foo (x,y)
select @x,@y
except
select x,y from foo

This will add a record to foo, ONLY if it is not already in the table.

You could try creating your index with the IGNORE_DUP_KEY option so that you only get a warning when you have duplicate keys rather than a true error.

The other option and possibly the better one is to use the MERGE statement rather than insert. The MERGE statement let's you do Inserts, Updates and Deletes all in one statement and sounds like it should work out well for what you are trying to do.

Last but not least, as you said fix it in your app and only insert the rows that need to be added.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top