I need to perform an upsert from select like this but in SQL Server. I found someone doing an upsert in SQL Server here, but that's not from a select.
My query basically looks like this right now:
INSERT INTO (table1) (...)
SELECT (...)
FROM (table 2)
WHERE X NOT IN (SELECT Y from (table1) WHERE Y IS NOT NULL)
But I can't figure out how to add the update part. I would like to add the update part after since 99% of the time it will be an insert.
Edit: this code would work if I was able to do it from a SELECT
:
BEGIN TRY
INSERT INTO table1 (id, name, itemname, itemcatName, itemQty)
VALUES ('val1', 'val2', 'val3', 'val4', 'val5')
END TRY
BEGIN CATCH
UPDATE table1
SET name = 'val2',
itemname = 'val3',
itemcatName = 'val4',
itemQty = 'val5'
WHERE id = 'val1'
END CATCH