27

我想使用Select语句根据第二个表中的值更新表中的多个列,以获取如下值:

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

但是,似乎不可能“设置”多个列名 - 是否有替代方法而不是为每一列编写单独的更新语句?

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'
4

3 回答 3

40
update tbl1
set col1 = a.col1, col2 = a.col2, col3 = a.col3
from tbl2 a
where tbl1.Id = 'someid'
and a.Id = 'differentid'
于 2013-04-08T14:28:00.900 回答
8

这应该工作 -

    Update Tbl1 
    SET 
    Col1 = B.ColA,
    Col2 = B.ColB,
    Col3 = B.ColC
    FROM
    Tbl2 B
    Where
    B.Id = 'Someid'
于 2013-04-08T14:19:36.667 回答
-1

你可以在这里找到答案。

于 2020-01-28T14:21:54.387 回答