2017-09-22 70 views
0

我有兩個表:TB1和TB2。如何從另一個表中爲每行插入多行

對於TB1中的每一行,我想使用TB1中的某些值將N個行插入到TB2中。我怎麼做?

例如:

For each row in TB1 
{ 
    For N in 1-10 
    { 
    insert into TB2 (col1, col2, col3, col4) 
    values (N, TB1.Col1, 'Good job', TB1.Col2) 
    } 
    commit; 
} 
+0

您正在使用哪種[DBMS](https://en.wikipedia.org/wiki/DBMS)產品? Postgres的?甲骨文? 「_SQL_」只是一種查詢語言,而不是特定數據庫產品的名稱。 –

回答

0

創建一個表與您要使用的N個(永久或臨時),然後過加入這個名單與TB1。如果表名爲n_list與名爲N列,則:

insert into TB2 
    (col2, col2, col3, col4) 
select 
    N, 
    TB1.Col1, 
    'Good job', 
    TB1.Col2 
from 
    TB1 
    cross join n_list; 
0

您可以使用cross join。建立數字的表,然後:

with n as (
     select 1 as n union all select 2 . . . union all select 10 
    ) 
insert into tb2 (col1, col2, col3, col4) 
    select n.n, TB1.Col1, 'Good job', TB1.Col2 
    from tb1 cross join 
      n; 

需要注意以下幾點:

  • 創建n的語法通過數據庫而異。例如,MySQL不支持CTE,因此它需要是一個子查詢。 Oracle需要from dual,依此類推。
  • 要將行從一個表插入到另一個表中,您需要insert . . . select,而不是每行的insert . . . values

最後,一個通用的SQL方法使用上tb1 10遍:

insert into tb2 (col1, col2, col3, col4) 
    select 1, TB1.Col1, 'Good job', TB1.Col2 
    from tb1 
    union all 
    select 2, TB1.Col1, 'Good job', TB1.Col2 
    from tb1 
    union all 
    . . . 
    select 10, TB1.Col1, 'Good job', TB1.Col2 
    from tb1 ; 
0

在等待的建議,我決定閒逛,並最終利用循環光標和喜歡這一點,它的工作原理對我來說...雖然不知道它有多足夠。並感謝所有的建議。

DECLARE 
CURSOR myCursor IS 
    select col1, col2 from TB1; 
tmp_rec myCursor%rowtype; 
BEGIN 
FOR tmp_rec in myCursor 
    LOOP 
    FOR N IN 1 .. 10 
     LOOP 
     insert into TB2 (col1, col2, col3, col4) 
     values (N, TB1.col1, 'Good job', TB1.col2); 
    END LOOP; 
    COMMIT; 
    END LOOP; 
END; 
相關問題