I'm a PostgreSQL user that's new to SQL Server. I need to replicate ON DUPLICATE KEY UPDATE functionality (sometimes called UPSERT). I've got a table of users (simplified here) with age and sex.
Using this sample query, but changing the id as needed, the UPDATE functionality works, but the INSERT doesn't. There's no error, it just says 0 rows affected.
MERGE
users AS target
USING
(SELECT id FROM users WHERE id=222) AS source
ON
target.id = source.id
WHEN MATCHED THEN
UPDATE SET
target.id = source.id,
target.age = 33,
target.sex = 'M'
WHEN NOT MATCHED THEN
INSERT (id, age, sex) VALUES (222, 33, 'M')
;
If it matters (maybe there's some easier way), I'm using Python3 in linux.
P.S. I looked at the other UPSERT in SQL Server questions here in StackOverflow. That's how I got this syntax. I couldn't understand the problem here through them, though.