Matthew
Matthew

Reputation: 10444

How can I use SQL MERGE to upsert single row based on Id, without a source set

There are a number of questions on the proper use of the MERGE statement in SQL Server. They all use a table/set reference for the merge. Is this table reference necessary?

In my case I have a sproc with two parameters @myId and @myValue

I simply want an UPSERT into MyTable based on the column [MyId]

It seems strange that I would have to create a set with

USING (SELECT @myId AS myId) AS source

to proceed with the MERGE (upsert). Is this the only way?

EDIT: voted to close my own question as exact duplicated... but I think the other question's title made it difficult to find.

Upvotes: 0

Views: 2055

Answers (1)

muhmud
muhmud

Reputation: 4604

You can also use this syntax:

merge into MyTable mt
using (values (@myId, @myValue)) t(id, value) on mt.Id = t.id
when not matched then insert /* ... */

You're always going to need a set of some kind.

Upvotes: 3

Related Questions