比较 Oracle 中的两个表
Compare two tables in Oracle
我在 oracle 10g 中有两个表(table1、table2),具有相同的列(A、B、C),但数据不同,我想将 table1 中的 A 列和 B 列与列 And B 进行比较从table2,如果A和B相似我需要用table2的C列更新table1的C列,如果它们不相似,我就插入新行,我应该使用什么?
我尝试使用普通的 SQL 代码,当我有超过 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;
您可以在循环内使用合并语句。
或者简单的 update\insert 像这个例子一样循环:
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;
(代表OP发表).
解决方案编号 1:合并语句
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:游标和 for 循环
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;
我在 oracle 10g 中有两个表(table1、table2),具有相同的列(A、B、C),但数据不同,我想将 table1 中的 A 列和 B 列与列 And B 进行比较从table2,如果A和B相似我需要用table2的C列更新table1的C列,如果它们不相似,我就插入新行,我应该使用什么?
我尝试使用普通的 SQL 代码,当我有超过 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;
您可以在循环内使用合并语句。
或者简单的 update\insert 像这个例子一样循环:
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;
(代表OP发表).
解决方案编号 1:合并语句
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:游标和 for 循环
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;