Sql server update multiple columns from another ta

2020-07-03 09:18发布

I have read lots of post about how to update multiple columns but still can't find right answer.

I have one table and I would like update this table from another table.

Update table1 
set (a,b,c,d,e,f,g,h,i,j,k)=(t2.a,t2.b,t2.c,t2.d,t2.e,t2.f,t2.g,t2.h,t2.i,t2.j,t2.k)
from 
(
  SELECT ..... with join ... where .... 

) t2
    where table1.id=table2.id

If I running only select statement (between brackets) then script return values but not working with update

3条回答
我欲成王,谁敢阻挡
2楼-- · 2020-07-03 09:55

TSQL does not support row-value constructor. Use this instead:

UPDATE table1 
SET a = t2.a,
    b = t2.b,
    (...)
FROM 
(
SELECT ..... with join ... WHERE .... 
) t2
WHERE table1.id = table2.id
查看更多
放我归山
3楼-- · 2020-07-03 10:05

The UPDATE SET commands implicitly apply on the table specified by , and it is not possible to specify the table on the SET operation.

Edit: Specify only the column name you want to update, do not mention the table.

查看更多
乱世女痞
4楼-- · 2020-07-03 10:09

You don't need to use a sub-query you can also simply do the following....

Update t1 
set t1.a  = t2.a
   ,t1.b  = t2.b
   ,t1.c  = t2.c
   ,t1.d  = t2.d
   .......
from table1 t1
JOIN table2 t2  ON t1.id = t2.id
WHERE .......
查看更多
登录 后发表回答