【问题标题】:Compare two tables in Oracle比较Oracle中的两个表
【发布时间】:2017-03-30 17:38:30
【问题描述】:

我在 oracle 10g 中有两个表(table1,table2),具有相同的列(A,B,C),但数据不同,我想将 table1 中的 A 和 B 列与 table2 中的列和 B 进行比较,如果A和B相似我需要用table2中的C列更新table1的C列,如果它们不相似,我只是插入新行,我应该使用什么?

我尝试使用普通的 SQL 代码,当我有超过 1 个类似的行时不起作用,我应该使用什么来遍历整个表?

【问题讨论】:

    标签: oracle plsql sqlplus


    【解决方案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;
    

    【讨论】:

    • 非常感谢,对我帮助很大!
    • @halfer 现在可以了吗?
    【解决方案2】:

    (代表 OP 发布).

    解决方案一:合并语句

    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);
    

    解决方案二:游标和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;
    

    【讨论】:

      【解决方案3】:

      您可以在循环中使用合并语句。

      或者像这个例子一样简单的更新\插入循环:

      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;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-20
        • 1970-01-01
        • 2014-09-17
        • 1970-01-01
        • 2014-05-09
        • 1970-01-01
        • 2017-07-10
        • 2021-10-16
        相关资源
        最近更新 更多