I ran into the following problem:
I am trying to save a table in sql server synchronized with several external databases. These external databases do not have a common unique primary key, so the local table has a simple integer PK.
Now, to update the local table, follow these steps:
- External databases requested.
- Data is converted to valid data for the local table.
- Insert is used to try to write data to a local table.
- If the insert returns a duplicate write exception, PK will search for a selection request and the data will be written to the table at the update request.
- Another table is modified using a PK inserted or updated row.
Now it works great, but to me it seems very inefficient. In most cases, the data is already in the local table and leads to duplication of the key exception in the insert. This means a lot of exceptions that need to be handled, which is expensive. In addition, because PK is controlled by the database, a select query must be used to find the row to be updated.
How can I avoid this effect? I donโt want to use the stored procedure, because I like to keep the request code-driven and included in version control.
I looked at the merger, but I saw too many people who reported problems with it.
I think I need to use the upsert form, but I'm not sure how to do this, since PK is managed by the database.
tl; dr: I need a query that will allow me to either insert or update a row (depending on the duplicate key or not), which will always return PK rows.
source share