[英]Compare the same multiple columns of two table in Oracle DB
我有两个表表 1 和表 2,有共同的列(a、b、c 和 d)。 什么要求是我需要匹配所有这 4 列(所有 4 列都应该匹配)。 如果这些匹配,则作业将运行,否则作业将不运行。
我是这样理解这个问题的。
首先,您应该指定您使用的数据库; PL/SQL 的意思是“Oracle”。
示例表:
SQL> select * From table1;
A B C D
---------- ---------- ---------- ----------
1 10 100 1000
2 20 200 2000
SQL> select * From table2;
A B C D
---------- ---------- ---------- ----------
1 10 100 1 --> column D is different
2 20 200 2000
以下查询使用集合运算符并检查是否存在table1
存在而table2
不存在的任何行,反之亦然。 如果是这样,则意味着不相等并且查询不会返回任何行(因此您不会运行该“作业”)。
SQL> select dummy
2 from dual
3 where not exists ((select a, b, c, d from table1
4 minus
5 select a, b, c, d from table2
6 )
7 union all
8 (select a, b, c, d from table2
9 minus
10 select a, b, c, d from table1
11 )
12 );
no rows selected
好的; 现在让我们使表相等,然后再试一次:
SQL> update table2 set d = 1000 where a = 1;
1 row updated.
SQL> select * From table1;
A B C D
---------- ---------- ---------- ----------
1 10 100 1000
2 20 200 2000
SQL> select * From table2;
A B C D
---------- ---------- ---------- ----------
1 10 100 1000 --> column D is now equal to table1's D column
2 20 200 2000
查询结果:
SQL> select dummy
2 from dual
3 where not exists ((select a, b, c, d from table1
4 minus
5 select a, b, c, d from table2
6 )
7 union all
8 (select a, b, c, d from table2
9 minus
10 select a, b, c, d from table1
11 )
12 );
D
-
X --> right; something is returned so - run the job!
SQL>
由于这是一个 PL/SQL问题,只需将这样的查询放入一个过程中:
SQL> create or replace procedure p_run is
2 l_dummy dual.dummy%type;
3 begin
4 select dummy
5 into l_dummy
6 from dual
7 where not exists ((select a, b, c, d from table1
8 minus
9 select a, b, c, d from table2
10 )
11 union all
12 (select a, b, c, d from table2
13 minus
14 select a, b, c, d from table1
15 )
16 );
17 dbms_output.put_line('Run the job!');
18 exception
19 when no_data_found then
20 dbms_output.put_line('Do nothing; tables aren''t equal');
21 end;
22 /
Procedure created.
测试:
SQL> rollback;
Rollback complete.
SQL> exec p_run;
Do nothing; tables aren't equal
PL/SQL procedure successfully completed.
SQL> -- let's make columns D equal as well
SQL> update table2 set d = 1000 where a = 1;
1 row updated.
SQL> exec p_run;
Run the job!
PL/SQL procedure successfully completed.
SQL>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.