如何从表中逐个获取值(id)

时间:2013-09-26 06:16:05

标签: sql-server-2008

请告诉我如何从表中获取一个值并将此值插入另一个表中。

Table1     Table2
Col1       Col1  Col2 
10         16    Null 
4          17    Null
8
9

我想在Table2中插入值,如下所示。

    Table2
    column 1   column 2
    10          16
    10          17
    4           16
    4           17
    8           16
    8           17
    9           16
    9           17

2 个答案:

答案 0 :(得分:1)

INSERT INTO table2 
SELECT t1.col1, 
       t2.col2 
FROM   (SELECT Row_number() 
                 OVER( 
                   ORDER BY (SELECT 0)) rno, 
               * 
        FROM   table1) t1 
       CROSS JOIN table2 t2 
ORDER  BY t1.rno  
Go
delete from table2 where col2 is null

答案 1 :(得分:0)

您可以使用cross join

<强> Fiddle demo

insert into table2
select t1.col1 , t2.col1 col2
from table1 t1 cross join table2 t2;


--if you don't need null values
delete table2 where col2 is null;

--results
select * from table2;