简体   繁体   中英

Update column in one table with values from different table without adding new rows

I have two tables and one common column named code in both the tables. I want to update the values of a column named version in table A with column named set_version values in table B.But this should not add rows and only update values. How do I do that?

You would use update with join :

update a
    set version = b.set_version
    from a join
         b
         on <some join condition here that your question does not specify>;

The update only updates existing rows. It does not add new rows to the table.

All the above answers were correct.But to make it more perfect I would like to answer my question so that if anyone reads then he/she should get it in one glance....

What I have :

There are two tables 'A' and 'B' with one common column 'Code'

What I want :

  • Put the values in the column named 'Version' of table 'A' from the column named 'Set_version' of table 'B.
  • And there is a common column between table 'A' and 'B' named 'Code'.
  • Only if the values match in the common columns then only impact the rows of the column named 'Version' in table 'A' with values in 'Set-version' of table 'B' without adding new rows in the table.If there are no rows matching then there should be no impact.

Solution:

Structure in general

UPDATE        targetTable
SET           targetTable.targetColumn = s.sourceColumn
FROM          targetTable t
INNER JOIN    sourceTable s
ON            t.matchingColumn = s.matchingColumn

Structure using my table and coumn names

UPDATE        dbo.A
SET           dbo.A.Version = s.Set_version
FROM          dbo.A t
INNER JOIN    dbo.B s
ON            t.Code = s.Code

This will definitely help the one with my scenario!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM