2013-07-01 37 views
0

我有一個從3個不同的表中返回數據的存儲過程。每次我在我的代碼中調用該過程時,我都希望它將任何新數據插入到不同的表中(我知道重複數據不是最佳實踐,但在這種情況下是需要的)。如何將存儲過程中的行插入表中,如果它們不存在?

這是我到目前爲止有:

BEGIN 

DECLARE 
v_cc COMM_CUSTOMER%ROWTYPE; 

CURSOR c1 is 
SELECT d.customer_name, d.active, f.street, f.state, f.zip, t.amount_due, t.due_date 
FROM tables t 
INNER JOIN othertable on ect, ect 
WHERE t.due_date < sysdate 
c_row c1%rowtype; 

BEGIN 
     OPEN c1; 
     LOOP 
     FETCH c1 
      INTO c_row; 
     EXIT WHEN c1%NOTFOUND; 
     MERGE INTO COMM_CUSTOMER cc 
     USING DUAL 
on (cc.customer_name= v_cc.customer_name and 
    cc.active = v_cc.active and 
    cc.street = v_cc.street and 
    cc.amount_due = v_cc.amount_due) 

when not matched then 
     insert values c_row; 

    COMMIT; 
    END LOOP; 
    CLOSE c1; 

這編譯,但什麼都不做。

我一直在使用oracle一個星期左右,不知道有關遊標和整體沒有太多的經驗與SQL ...有人可以告訴我我做錯了/另一種方式做這個?謝謝!

回答

0

試試這個:

DECLARE 
    v_cc COMM_CUSTOMER%ROWTYPE; 
    CURSOR c1 
    IS 
      SELECT d.customer_name, 
       d.active, 
       f.street, 
       f.state, 
       f.zip, 
       t.amount_due, 
       t.due_date 
      FROM tables t 
      INNER JOIN othertable 
      ON (ect   = ect1) 
      WHERE t.due_date < sysdate; 
    c_row c1%rowtype; 
BEGIN 
OPEN c1; 
LOOP 
    fetch c1 into c_row; 
    exit when c1%notfound; 

merge into comm_customer cc 
using dual 
ON (cc.customer_name= v_cc.customer_name AND cc.active = v_cc.active AND cc.street = v_cc.street AND cc.amount_due = v_cc.amount_due) 
WHEN NOT matched THEN 
    INSERT 
      (col1_name, col2_name 
     )VALUES 
      (c_row.customer_name, c_row.active 
     ); 
    COMMIT; 
END LOOP; 
CLOSE c1; 
END; 
0

嘗試這樣的事:

merge into COMM_CUSTOMER cc 
using 
(
    SELECT d.customer_name, d.active, f.street, f.state, f.zip, t.amount_due, t.due_date 
    FROM tables t 
    INNER JOIN othertable on ect, ect 
    WHERE t.due_date < sysdate 
) input 
on (cc.customer_name= input.customer_name and 
    cc.active = input.active and 
    cc.street = input.street and 
    cc.amount_due = input.amount_due) 
when not matched then 
     insert values cc.customer_name, cc.active, cc.street, cc.state, cc.zip, cc.amount_due, cc.due_date; 

你應該閱讀更多關於merge clause

相關問題