2012-05-16 53 views
2

我在PL/SQL中創建了一個過程,它根據主鍵將數據從一個表插入另一個表。我的程序工作正常,但我無法弄清楚如果主鍵已經存在,我將如何更新我的表MAIN的列CODE_NUMBER。
其實我想要MAIN表的行時得到更新,當它有主鍵,並從主要關鍵字不存在時從區域插入數據。在PL/SQL中插入/更新

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; 

回答

1

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

--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 
    ) 
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) 

瞭解更多關於SQL MERGE聲明的文檔中