Let's say I have a table and I want to insert a row. The new row's key may already match an existing row's key in the table, in which case I want to update the existing row. Or, it may not exist in the table, in which case the new row should be inserted.
What is the most efficient way to perform such an operation? I was thinking of first doing a SELECT
(perhaps with EXISTS
) to see if a particular key is present, followed by an UPDATE
if present and an INSERT
if not. You would probably need to keep an UPDLOCK
and a HOLDLOCK
for this combination of statements in order to avoid race conditions, as well. This seems overly complicated and inefficient.
I was wondering if there was a more efficient way to do this in SQL Server 2008R2.