0

I have a table "Master" with fields called "DFM" and "Target". I ideally need 1 UPDATE query that will populate the "Target" field based on the value of DFM as below:

DFM Target

50001   85
50009   255
50011   233
50012   290
50062   183
50063   150
50064   159.5
50142   187
50143   174
50179   284.25
50180   195.75
50286   157.25
50287   231.25

For example if the DFM value is 50142 it should UPDATE the field for that row with 187.

So can this be done with 1 query, or do I need 13?

I only know the long winded way ie

UPDATE Master, SET Target = 85 WHERE DFM = 50001

I don't really want 13 queries though.

4
  • There seems to be some information missing. Your Master table already has the values for Target you want to update them to. As you looking to update the Target field on some other table based on the values on Master or the values on Master based on some other lookup table? Commented Jan 6, 2017 at 15:22
  • No, sorry if it isn't clear, the DFM is populated but not Target. The info I gave above was merely the data I wanted populating just so you can see what it looks like. Commented Jan 6, 2017 at 15:25
  • Then the solution given below (with my correction) should work. If target is not populated at all or if all your potential values for dfm have a replacement value inside the switch you can also skip the where part of it. Commented Jan 6, 2017 at 15:30
  • Many thanks for your help. Commented Jan 6, 2017 at 15:43

1 Answer 1

2

You can use a switch:

update master
    set target = switch(dfm = 50001, 85,
                        dfm = 50009, 255,
                        . . .
                       )
    where dfm in (50001, 50009, . . .);
Sign up to request clarification or add additional context in comments.

1 Comment

That should be switch(dfm=50001, 85, dfm=50009, 255, ...)

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.