簡體   English   中英

在PL / SQL中插入/更新

[英]Insert/Update in PL/SQL

我在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; 

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)

閱讀文檔中有關SQL MERGE語句的更多信息

在這種情況下,我無法真正看到做光標的重點。 為什么你不能這樣做:

--Update the rows
UPDATE MAIN
SET ID=regions.REGION_ID,
    CODE_NUMBER=regions.[description]
FROM MAIN
JOIN regions
    ON MAIN.ID=regions.REGION_ID;

--Insert the new ones
INSERT INTO MAIN(ID,CODE_NUMBER)
SELECT
    regions.REGION_ID,
    regions.[description]
FROM
    regions
WHERE NOT EXISTS
    (
        SELECT
            NULL
        FROM
            MAIN.ID=regions.REGION_ID
    )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM