在PL/SQL中插入/更新

Fem*_*ale 2 sql plsql oracle11g plsqldeveloper

我在PL/SQL中创建了一个过程,它根据主键将数据从一个表插入另一个表.我的程序工作正常,但我无法弄清楚如果主键已经存在,我将如何更新我的表MAIN列CODE_NUMBER.
实际上我希望MAIN表的行在其具有主键时获得UPDATED,并在主键不存在时从REGIONS插入数据.

DECLARE
    variable number;
    id number;
    description varchar2 (100);

    CURSOR C1 IS
        select regions.REGION_ID variable
        from regions;

BEGIN
      FOR R_C1 IN C1 LOOP
            BEGIN
                select regions.REGION_ID,regions.REGION_NAME
                into id,description
                from regions
                where regions.REGION_ID = R_C1.variable; 
                ----If exists then update otherwise insert
                INSERT INTO MAIN( ID, CODE_NUMBER) VALUES( id,description);
                dbms_output.put_line( id ||' '|| 'Already Exists');
            EXCEPTION
                WHEN DUP_VAL_ON_INDEX THEN
                dbms_output.put_line( R_C1.variable);
            END;
      END LOOP;
END; 
Run Code Online (Sandbox Code Playgroud)

Luk*_*der 7

PL/SQL和游标不需要这样做.你真正想要做的是这样的事情:

MERGE INTO MAIN dst
USING (
  SELECT regions.REGION_ID id,
         regions.REGION_NAME description
  FROM   regions
) src
ON src.id = dst.id
WHEN MATCHED THEN UPDATE 
  SET dst.code_number = src.description
WHEN NOT MATCHED THEN INSERT (id, code_number)
  VALUES (src.id, src.description)
Run Code Online (Sandbox Code Playgroud)

阅读SQL MERGE文档中有关该语句的更多信息