简体   繁体   中英

How can I replace values inside a temp table from another values inside another temp table?

I have two temp tables. First one is the following:

Column1 |Column2         |Column3       |Column4     |Column5     |Column6
--------|----------------|--------------|------------|------------|-------
 10      |11               |1111          |001         |345.000000  |22
 13      |12               |1111          |001         |700.000000  |22
 10      |14               |1112          |001         |345.000000  |22
 16      |15               |5454          |001         |1200.000000 |22
 16      |17               |2364          |001         |1350.000000 |22

The second one contains the numbers which will replace the numbers in the first two columns:

Column1 |Column2         |
--------|----------------|
 10      |1               |
 11      |2               |
 12      |5               |
 13      |3               |
 14      |0               |
 15      |7               |
 16      |2               |
 17      |5               |

I have to alter the first table (first two columns of it) in order to replace the numbers by their corresponding new values

The result will be as follow:

Column1 |Column2         |Column3       |Column4     |Column5     |Column6
--------|----------------|--------------|------------|------------|-------
 1      |2               |1111          |001         |345.000000  |22
 3      |5               |1111          |001         |700.000000  |22
 1      |0               |1112          |001         |345.000000  |22
 2      |7               |5454          |001         |1200.000000 |22
 2      |5               |2364          |001         |1350.000000 |22

AND I am completely stuck

I would use an updatable CTE with a join:

WITH cte AS (
    SELECT t1.Column1 AS col1_target, t2_a.Column2 AS col1_src,
           t1.Column2 AS col2_target, t2_b.Column1 AS col2_src
    FROM #temp1 t1
    INNER JOIN #temp2 t2_a ON t1.Column1 = t2_a.Column1
    INNER JOIN #temp2 t2_b ON t1.Column2 = t2_b.Column2
)

UPDATE cte
SET
    col1_target = col1_src,
    col2_target = col2_src;

You can use two left join s:

update t1
    set t1.column1 = t2_1.column2,
        t1.column2 = t2_2.column2
    from table1 t1 left join
         table2 t2_1
         on t1.column1 = t2_1.column1 left join
         table2 t2_2
         on t1.column2 = t2_2.column1
    where t2_1.column1 is not null or t2_1.column2 is not null

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