Oracle更新现有记录或插入新记录

时间:2017-02-23 04:00:08

标签: oracle plsql

我有一个像这样定义的表:

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;
/

1 个答案:

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