2015-08-03 62 views
-2

之間的比較這是一個例子,我需要:PL/SQL:過程來處理兩個表

表1:

Id champ1 champ2 champ3 
    1  A  S  Q 
    2  D  K  A 
    3  D  A  S 

表2:

Id champ1 champ2 champ3 
    1  A  S  Q 
    2  Q  A  A 
    3  A  A  K 

一個程序,通過表1和表2之間的比較結果饋送表3

表3:

Id_exc name_champ noted_val except_val 
    2 champ1  D   Q 
    3 champ1  D   A 
    2 champ2  K   A 
    3 champ3  S   K 

請,我需要幫助,如果有人有相同的挑戰:)先進

+0

什麼樣的比較? – Hawk

+0

我需要比較表1上的數據和表2上的數據,如果兩個表中的數據不相同,則此過程會提供表3。 – user3441432

+0

@ user3441432你對這個問題的描述是相當不錯的,如果你將包括你所嘗試過的投票可能會在另一個方向去。 – maraca

回答

1

數據建立

感謝:

CREATE TABLE Table1 
    (Id int, champ1 varchar2(1), champ2 varchar2(1), champ3 varchar2(1)) 
; 

INSERT ALL 
    INTO Table1 (Id, champ1, champ2, champ3) 
     VALUES (1, 'A', 'S', 'Q') 
    INTO Table1 (Id, champ1, champ2, champ3) 
     VALUES (2, 'D', 'K', 'A') 
    INTO Table1 (Id, champ1, champ2, champ3) 
     VALUES (3, 'D', 'A', 'S') 
SELECT * FROM dual 
; 

CREATE TABLE Table2 
    (Id int, champ1 varchar2(1), champ2 varchar2(1), champ3 varchar2(1)) 
; 

INSERT ALL 
    INTO Table2 (Id, champ1, champ2, champ3) 
     VALUES (1, 'A', 'S', 'Q') 
    INTO Table2 (Id, champ1, champ2, champ3) 
     VALUES (2, 'Q', 'A', 'A') 
    INTO Table2 (Id, champ1, champ2, champ3) 
     VALUES (3, 'A', 'A', 'K') 
SELECT * FROM dual 
; 

下面的查詢會給你的差異

SELECT * 
FROM ((SELECT * 
     FROM table1 
     minus 
     SELECT * 
     FROM table2) 
     UNION 
     (SELECT * 
     FROM table2 
     minus 
     SELECT * 
     FROM table1)); 

ID CHAMP1 CHAMP2 CHAMP3 
2 D K A 
2 Q A A 
3 A A K 
3 D A S 
+0

非常感謝你 – user3441432

+0

該查詢給出了差異,但我需要一個查詢或過程與PL/SQL飼料表3與兩個表之間的差異 – user3441432

1

Fiddle here.

這裏是一個查詢,得到的結果,但它的醜陋:

SELECT 
    t1.id AS Id_exc, 'champ1' AS name_champ, t1.champ1 AS noted_val, t2.champ1 AS except_val 
FROM 
    Table1 t1 INNER JOIN Table2 t2 ON t2.id = t1.id WHERE t1.champ1 <> t2.champ1 

UNION 

SELECT 
    t1.id AS Id_exc, 'champ2' AS name_champ, t1.champ2 AS noted_val, t2.champ2 AS except_val 
FROM 
    Table1 t1 INNER JOIN Table2 t2 ON t2.id = t1.id WHERE t1.champ2 <> t2.champ2 

UNION 

SELECT 
    t1.id AS Id_exc, 'champ3' AS name_champ, t1.champ3 AS noted_val, t2.champ3 AS except_val 
FROM 
    Table1 t1 INNER JOIN Table2 t2 ON t2.id = t1.id WHERE t1.champ3 <> t2.champ3 
+0

代碼不看起來那麼醜陋,但絕對服務於此目的。所以+ 1 – SriniV

+0

@realspirituals感謝您加入小提琴,我發現您的比較方式也很有趣,它更加動態。 +1 – maraca

+0

謝謝你的幫助 – user3441432

0

創建或替換程序P_test是

q VARCHAR2(4000字節);

V_SELECT VARCHAR2(2000):= NULL;

開始在

爲REC(選擇從USER_TAB_COLUMNS COLUMN_NAME在表格名= 'TABLE1' 和列名<> 'ID_T')環

V_SELECT:= NULL;

V_SELECT:= V_SELECT || rec.COLUMN_NAME;

q:='SELECT t1.id_t AS Id,'''|| V_SELECT ||'''AS nom_champ,t1。'|| V_SELECT ||'如上所述,t2。'|| V_SELECT ||' AS例外'||

'FROM TABLE1 t1 INNER JOIN TABLE2 t2 ON t1.id_t = t2.id_t WHERE t1。'|| V_SELECT ||' <> t2。'|| V_SELECT;

q:='INSERT INTO TABLE3'|| q;

dbms_output.put_line('Query:'|| q);

立即執行q;

end loop; 結束;