简体   繁体   中英

How do I insert values from one table into another without a value to inner join them?

Table A has a single field. Table B has many fields.

I want to copy each value from Table A to a row on Table B but I have no values with which to join the two tables.

It doesn't matter which row in B each value in A goes into as long as each value in Table A only appears once in Table B.

I do not want to use loops.

You could assign a row number to each of the two tables, and then do an update join:

WITH cte1 AS (
    SELECT col, ROW_NUMBER() OVER (ORDER BY col) rn
    FROM TableA
),
WITH cte2 AS (
    SELECT *,
           ROW_NUMBER() OVER (ORDER BY some_col) rn
    FROM TableB
)
UPDATE t2
SET col = t1.col
FROM cte2 t2
INNER JOIN cte1 t1
    ON t1.rn = t2.rn

This solution makes several assumptions, including that TableB already has a destination column col for the data coming from the first TableA table's single column, and that the types match in both tables. It also assumes that TableB has more rows than TableA to fit the data from TableB . If not, data would be lost.

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