29

I would like to update multiple columns in a table based on values from a second table using a Select statement to obtain the values like this:

UPDATE tbl1 
SET (col1, col2, col3) = (SELECT colA, colB, colC 
                          FROM tbl2 
                          WHERE tbl2.id = 'someid') 
WHERE tbl1.id = 'differentid'

However, it doesn't seem as though it's possible to 'SET' more than one column name - are there alternatives rather than writing separate update statements for each column?

UPDATE tbl1 
SET col1 = (SELECT colA FROM tbl2 WHERE tbl2.id = 'someid') 
WHERE tbl1.id = 'differentid'

UPDATE tbl1 
SET col2 = (SELECT colB FROM tbl2 WHERE tbl2.id = 'someid') 
WHERE tbl1.id = 'differentid'

UPDATE tbl1 
SET col3 = (SELECT colC FROM tbl2 WHERE tbl2.id = 'someid') 
WHERE tbl1.id = 'differentid'
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Prakash Chennupati
  • 3,066
  • 3
  • 27
  • 38

3 Answers3

41
update tbl1
set col1 = a.col1, col2 = a.col2, col3 = a.col3
from tbl2 a
where tbl1.Id = 'someid'
and a.Id = 'differentid'
Tevo D
  • 3,351
  • 21
  • 28
7

This should work -

    Update Tbl1 
    SET 
    Col1 = B.ColA,
    Col2 = B.ColB,
    Col3 = B.ColC
    FROM
    Tbl2 B
    Where
    B.Id = 'Someid'
Arun
  • 969
  • 7
  • 17
-1

You can find the answer here.

Ahmed Eissa
  • 1,139
  • 1
  • 8
  • 14