2014-10-27 58 views
0

想想我的两个表具有相同的列。一列是ID,另一列是文本。是否有可能在PLSQL中实现以下伪代码?比较两个表,如果行不同,请在Oracle中运行查询

Compare each row (They will have the same ID) 
    If anything is different about them 
     Run a couple of queries: an Update, and an Insert 
    ElseIf they are the same 
     Do nothing 
    Else the row does not exist 
     So add the row to the table compared on 

使用PLSQL很容易做到这一点,还是应该创建一个独立的应用程序来执行此逻辑。

+0

您是否试过[MERGE](http://oracle-base.com/articles/9i/merge-statement.php)声明? – user75ponic 2014-10-28 05:03:40

回答

3

当你的表具有相同的列,由使用NATURAL JOIN您可以轻松检查两个相应的行是否相同 - 如果列中添加了列,则无需更新代码。

此外,使用OUTER JOIN可以查找一个表中存在但不存在于另一个表中的行。

所以,你可以使用类似的东西来达到你的目的:

for rec in (
    SELECT T.ID ID1, 
      U.ID ID2, 
      V.EQ 
      FROM T 
      FULL OUTER JOIN U ON T.ID = U.ID 
      FULL OUTER JOIN (SELECT ID, 1 EQ FROM T NATURAL JOIN U) V ON U.ID = V.ID) 
loop 
    if rec.id1 is null 
    then 
     -- row in U but not in T 
    elsif rec.id2 is null 
    then 
     -- row in T but not in U 
    elsif rec.eq is null 
     -- row present in both tables 
     -- but content mismatch 
    end if 
end loop 
+0

喜欢你的答案,但是EQ可以比较表格的多个列吗?就像我想比较'ID,文本,数字'列? – lzc 2014-10-28 15:45:01

+0

@lzc'不确定如何理解您的评论,但是使用NATURAL JOIN,您将比较两个表中具有相同名称的_all_列。 – 2014-10-28 16:21:58

+0

进行了一些测试,'U.ID = V.ID'比较ID是否不同,如果它们不同则EQ返回null,如果它们相同则返回1 – lzc 2014-10-28 17:05:05

0

只需使用MINUS

 
query_1 
MINUS 
query_2 

在你的情况,如果你真的想用PL/SQL,然后select count into a local variable。写一个逻辑,if count > 0 then do other stuff

1
Else the row does not exist 
    So add the row to the table compared on 

此条件是否意味着在两个表中都可能会丢失行?如果只有一个,那么:

insert into t1 (id, text) 
select id, text 
from t2 
minus 
select id, text 
from t1; 

如果在两个表中都有错过的记录,则需要从t1插入到表t2行中的相同查询。

If anything is different about them 

如果您需要对不同行的任何数量的一个动作,然后用这样的:

select count(*) 
into a 
from t1, t2 
where t1.id = t2.id and t1.text <> t2.text; 
if a > 0 then 
    ... 

否则:

for i in (
    select * 
    from t1, t2 
    where t1.id = t2.id and t1.text <> t2.text) loop 

    <do something> 

end loop; 
1

A“合并”语句是你所需要的东西。

下面是语法:

MERGE INTO TARGET_TABLE 
USING SOURCE_TABLE 
ON (CONDITION) 
WHEN MATCHED THEN 
UPDATE SET (DO YOUR UPDATES) 
WHEN NOT MATCHED THEN 
(INSERT YOUR NEW ROWS) 

谷歌合并语法更多有关语句。

+0

可以合并语句'WHEN MATCHED THEN':'UPDATE和INSERT' ? – lzc 2014-10-28 13:19:12

+0

你的问题是什么? – theDbGuy 2014-10-29 03:52:09

+0

我尝试在'WHEN MATCHED THEN'下的Update和Insert语句中滑动,因为基本上我正在更新当前行以显示其'已删除',然后插入一个具有值的新行 – lzc 2014-10-29 13:37:25

相关问题