Search code examples
sqlsql-serversql-updatemultiple-records

how to copy data from multiple rows of one table to another in sql server?


I have 2 tables with the following structure:

Table A:

id_A    col1
 1      val1
 2      val2
 3      val3
 ...    ....

Table B:

id_B  mycol   id_A_val
 1    smval1    null
 2     null      1
 3     null      2
...    ...       ...

I want to copy values from Table A's col1 into Table B's mycol This is my expected result:

Expected:

id_B  mycol   id_A_val
 1    smval1    null
 2    val1      1
 3    val2      2
...    ...      ...

I tried several combinations of SQL UPDATE. This was the latest I tried - but it throws an error saying "Subquery returned more than 1 value."

Tried:

UPDATE [dbo].[Table_B] 
SET MYCOL = (SELECT inst.[COL1] FROM [dbo].[TABLE_A] a,  [dbo].[TABLE_B] b
WHERE a.[ID_A] = b.[ID_A_VAL] AND b.ID_A_VAL IS NOT NULL)

Can someone throw some light on the correct direction to get a working query?


Solution

  • Try this:

    update
        b
    set
        mycol=table_a.col1
    from table_b b
    inner join table_a on
        b.id_A_val=table_a.id_A