SQL Server - update column based on another column value

Fearghal picture Fearghal · Sep 2, 2013 · Viewed 8k times · Source

How can I update a column in TableA value found in another table, Table B, depending on another column, Type, in TableA

E.g.

Table A

Location Type Value
  USA    Dog   20
  UK     Cat   30

Table B

Dog   Cat Rabbit
 50   70    100

Logic:

  • If tableA.Value = Dog then update TableA.Value = TableB.Dog
  • If tableA.Value = Cat then update TableA.Value = TableB.Cat
  • If tableA.Value = Rabbit then update TableA.Value = TableB.Rabbit

Note: There is only 3 options so hard coding is ok.

Result

Table A

Location Type  Value
USA      Dog   50
UK       Cat   70

Answer

Adriaan Stander picture Adriaan Stander · Sep 2, 2013

How about something like

UPDATE TableA
SET Value = 
CASE Type
  WHEN 'DOG' then B.Dog
  WHEN 'CAT' then B.Cat
  WHEN 'RABBIT' then B.Rabbit
  ELSE Value
END
FROM TableB b

SQL Fiddle DEMO