0

I have a table that looks like:

Attributes
------------------------------------
Id | UserId | Key | Value | Active |

I would like to insert a new row into this table, and for every row that has the same UserId and Key, I'd like to set Active to 0.

The merge statement seems like a convenient choice here, but I'm not sure how to perform two actions at once, ie:

MERGE INTO Attributes AS Target
USIN (<values>) AS Source (<columns>)
    ON Target.Key = Source.Key AND Target.UserId = Source.Uid
WHEN MATCHED <update, then insert>
WHEN NOT MATCHED <insert>

I could definitely do this in two queries, but I was wondering if there's a way to do what I'm proposing in one.

1
  • It's still two separate actions, so what is the gain in using one statement? Also please read this in full. MERGE does not buy you anything here. Commented Apr 21, 2015 at 19:05

1 Answer 1

2

You could possibly do it in a single MERGE statement, but it won't be pretty. MERGE will perform only one action for every row in Source, so it won't do both MATCHED and NOT MATCHED and you can't both update and insert for MATCHED; you would need to select one row for every existing row, plus one row for the row you actually want to insert in order to do what you want using just a MERGE.

You are better off just using 2 queries.

Sign up to request clarification or add additional context in comments.

6 Comments

Good call. I'll use two queries.
I'm pretty sure you can do MATCHED and NOT MATCHED in the same MERGE statement. WHEN MATCHED THEN <do something> WHEN NOT MATCHED THEN <do something else>
Yes, I meant that for each row, MERGE only does one or the other.
Yeah sorry I just reread your answer and realized that's what you meant.
Either way I think Ben Jaspers is right; I should be doing this in two queries for readability if nothing else. This won't be a common enough action for extra overhead to matter (and a merge that complex might be inefficient on its own anyway).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.