如果它们尚不存在,如何将存储过程中的行插入表中?

时间:2013-07-01 03:39:08

标签: oracle plsql

我有一个存储过程,可以从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没有多少经验...有人能告诉我我做错了什么/另一种做法吗?谢谢!

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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

的更多信息