2015-10-11 36 views
0

基本概念是複製table1中的行,其中id之間例如100..10000, 修改某些列數據,然後插入新的ID:通過多個表(新ID /外鍵)複製行並進行一些列修改

表2引用table1.id與外鍵,table3引用table2.id與外鍵 ....和tableX引用tableX-1.id與外鍵。 我也有一些table2..tableX數據的modificate。

我開始考慮編寫嵌套循環;前3臺,它看起來像這樣(在PLSQL),或許它應該工作:

declare 
table1_row table1%rowtype; 
table2_row table2%rowtype; 
table3_row table3%rowtype; 
begin 
    for t1 in(select * from table1 
    where id between 100 and 10000) 
    loop 
    table1_row:=t1; 
    table1_row.id:=tableseq.nextval; 
    table1_row.col1:='asdf'; 
    table1_row.col4:='xxx'; 
    insert into table1 values table1_row; 

    for t2 in(select * from table2 
    where foreign_key_id =t1.id) 
    loop 
     table2_row:=t2; 
     table2_row.id:=tableseq.nextval; 
     table2_row.foreign_key_id:=table1_row.id; 
     table2_row.col3:='gfdgf'; 
     insert into table2 values table2_row; 

     for t3 in(select * from table3 
     where foreign_key_id =t2.id) 
     loop 
      table3_row:=t3; 
      table3_row.id:=tableseq.nextval; 
      table3_row.foreign_key_id:=table2_row.id; 
      table3_row.col1:='gdfgdg'; 
      insert into table3 values table3_row;   
     end loop;  
    end loop;  
    end loop; 
end; 

沒有更好的辦法?大約有10-20個循環,看起來很糟糕:( 在此先感謝。

+0

哪個d atabase和哪個版本? –

回答

0

我相信你可以使用一個插入語句和幾個子查詢來清理這個。這裏是一個更簡單的例子,但我相信你可以推斷你的具體案例:

insert into table1 
(col1, col2, col3, col4, col5) 
values 
select 'asdf', 
     (select table2_data --whatever data from this table you want 
      from table2 
     where foreign_key_id =table1.id), 
     (select table3_data --whatever data from this table you want 
      from table3 
     where foreign_key_id =table1.id), 
     'xxx', 
     table1.col5 
    from table1 
where table1.id between 100 and 10000 

注意,您的ID欄應設置爲一個AUTO_INCREMENT主鍵,所以你不應該需要它作爲你的INSERT語句的一部分,另外,我補充說:「table1.col5」爲例。如何使用你的重複行中現有行的相同數據(因爲我假設你想複製一些數據)。