2017-02-23 105 views
0

我有這樣定義的表:甲骨文更新現有的記錄或插入新

CIC3.WBCOURSEACTIVITY 
(
    WCA_RID   NUMBER, 
    WCA_TNA_ID  NUMBER, 
    WCA_REG_RID  NUMBER, 
    WCA_ANSWERED_PTS NUMBER, 
    WCA_TOTAL_PTS  NUMBER, 
    WCA_TITLE   VARCHAR2(50 BYTE) 
) 

我想更新,我送一個已經否則存在相同WCA_TNA_RID和WCA_REG_RID組合的任何記錄,我想插入一個新紀錄。我在WCA_RID上有一個序列

這看起來好像會做伎倆還是會更好?

CREATE OR REPLACE procedure CIC3.f_savewbpoints(pParticipantID number, pRegRid number, pAnsweredPoints number, pTotalPoints number, pTitle VARCHAR2) is 
    vWcaRid number; 
begin  
    SELECT DISTINCT wca_rid INTO vWcaRid 
    FROM wbcourseactivity 
    WHERE wca_reg_rid = pRegRid 
     AND wca_tna_id = pParticipantID; 

    UPDATE wbcourseactivity 
    SET wca_answered_pts = pAnsweredPoints 
     , wca_totalPts = pTotalPoints 
     , wca_title = pTitle 
    WHERE wca_rid = vWcaRid 
    IF (NVL(SQL%ROWCOUNT, 0) = 0) THEN 
      INSERT INTO wbcourseactivity (wca_tna_id 
             , wca_reg_rid 
             , wca_answered_pts 
             , wca_total_pts 
             , wca_title) 
      VALUES 
             (pParticipantID 
             , pRegRid 
             , pAnsweredPoints 
             , pTotalPoints 
             , pTitle); 
    END IF; 
    commit; 
end; 
/
+0

順便說一句'IF(NVL(SQL%ROWCOUNT,0)= 0)'可以簡化爲'如果SQL%ROWCOUNT = 0'。在SQL語句之後它不能爲空。 –

回答

2

你可以使用MERGE

CREATE OR REPLACE procedure CIC3.f_savewbpoints(pParticipantID number, pRegRid number, pAnsweredPoints number, pTotalPoints number, pTitle VARCHAR2) is 
begin 
    merge into wbcourseactivity a 
    using (
     SELECT DISTINCT wca_rid, wca_reg_rid, wca_tna_id 
     FROM wbcourseactivity 
     WHERE wca_reg_rid = pRegRid 
     AND wca_tna_id = pParticipantID; 
    ) b on (
     a.wca_rid = b.wca_rid 
     and a.wca_reg_rid = b.wca_reg_rid 
     and a.wca_tna_id = b.wca_tna_id 
    ) 
    when matched then update set a.wca_answered_pts = pAnsweredPoints 
    when not matched then insert (wca_tna_id, wca_reg_rid, wca_answered_pts, wca_total_pts, wca_title) 
         values (pParticipantID, pRegRid, pAnsweredPoints, pTotalPoints, pTitle); 
    commit; 
end; 
/
+0

試過了,它沒有工作。我寫的功能很好,只需稍作調整即可。如果你不介意的話,無論如何我會給你點數。 – MB34