2017-03-25 58 views
0

我在oracle 10g(table1,table2)中有兩個表,它們具有相同的列(A,B,C),但數據不同,我想比較table1中的A列和B列如果A和B類似,我需要更新table1的C列和來自table2的C列,如果它們不相似,我只需插入新行,我應該使用什麼?比較Oracle中的兩個表

我用普通的SQL代碼嘗試過,當我有超過1個類似的行時沒有工作,我應該用什麼來瀏覽整個表格?

回答

0

(發佈代表OP)的

解決方案NUMBER1:MERGE語句

merge into table1 A 
using table2 B 
on (A.A = B.A and A.B = B.B) 
when matched then 
update set A.C = B.C 
when not matched then 
insert (A,B,C) values(B.A,B.B,B.C); 

解決方案數字2:光標和循環

cursor cur is select * from table2; 
Begin 

For rec in cur Loop 

Update table1 Set c = rec.c Where a = rec.a and b= rec.b; 

If sql%rowcount = 0 then 
insert into table1(a,b,c) values(rec.a,rec.b,rec.c); 


End if; 

End loop; 
end; 
1

您可以使用PL/SQL來爲您提供任何靈活性。 PL/SQL的格式如下:

declare 
cursor a is select * from table1; 
cursor b is select * from table2; 

Begin 
For i in a 
Loop 
    for j in b 
    loop 
     if i.A=j.A & i.B=j.B then 
      ------DML operation 
    end loop; 
end Loop; 

end; 
+0

非常感謝你,這對我幫助很大! – zenami

+0

@halfer現在好嗎? – smshafiqulislam

+0

是的,那真是太棒了!感謝編輯。 – halfer

0

您可以使用合併語句insdie循環。

或簡單的在這樣一個例子循環更新\插入:

Begin 

For rec in (select * from table2) 
Loop 

Update table1 
Set c = rec.c 
Where a = rec.a and b= rec.b; 

If sql%rowcount = 0 then 
-- some insert 
... 
End if; 

End loop; 

End; 
+0

非常感謝,工作得非常好! – zenami