EDIT: This is just an simplified example, I know it seems really wrong, but thought this is the simpliest way to ask my question.
Let's say I have a Person
and an 'Email' table. Each person can have 2 e-mails.
Here is a small example:
For some reason, we decide to extend our Person
table with 2 columns: FirstEmail
, and SecondEmail
, so after an update, the results looks like something like this:
Can I UPDATE
the table with a single statement? For example, I tried this, but it doesn't work (doesn't give error, only the FirstEmail
is filled, the SecondEmail
is NULL
).
UPDATE Person
SET FirstEmail = CASE WHEN e.Type = 'FIRST' THEN e.Value ELSE FirstMail END,
SecondMail = CASE WHEN e.Type = 'SECOND' THEN e.Value ELSE SecondMail END
FROM Person p
INNER JOIN Email e ON (p.Id = e.PersonId);
And as I see MERGE
can't work with multiple rows, because I get this error for a similar approach:
The MERGE statement attempted to UPDATE or DELETE the same row more than once. This happens when a target row matches more than one source row. A MERGE statement cannot UPDATE/DELETE the same row of the target table multiple times. Refine the ON clause to ensure a target row matches at most one source row, or use the GROUP BY clause to group the source rows.