I have a process that I do not want to track if something is a create or an update. Tracking would be complex. I would like to perform a create OR update. The schema is like...
col1 varchar() (PK)
col2 varchar() (PK)
col3 varchar() (PK)
col4 varchar()
I am thinking about doing
TRY
{
INSERT ...
}
CATCH(DuplicateKeyException)
{
UPDATE ...
}
What do you suggest?
I want to ensure that I understand the other top voted answer. Given my schema, the UPDATE always occurs (even with an INSERT), but the insert only occurs where it does not exist?
//UPSERT
INSERT INTO [table]
SELECT [col1] = @col1, [col2] = @col2, [col3] = @col3, [col4] = @col4
FROM [table]
WHERE NOT EXISTS (
-- race condition risk here?
SELECT 1
FROM [table]
WHERE [col1] = @col1
AND [col2] = @col2
AND [col3] = @col3
)
UPDATE [table]
SET [col4] = @col4
WHERE [col1] = @col1
AND [col2] = @col2
AND [col3] = @col3