[英]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.