仅当Oracle PLSQL不存在时才插入。

时间:2012-10-02 16:37:40

标签: sql oracle plsql insert

  

可能重复:
  oracle insert if row not exists

我正在使用下面的查询来计算某些数据的总数,但是,我希望只有在首先在EL_CLIENT_REC_UNITS中不存在ID时才执行插入。任何人都可以看到这样做的方法吗?

     INSERT INTO EL_CLIENT_REC_UNITS 
     (ID,
     EL_CLIENT_ID,
     RECORDING_ID,
     UNIT_TYPE,
     PHY_DIG_OR_TOTAL,
     CONTROLLED_PERCENTAGE,
     PERC_ADJ_UNITS_RECEIVED,
     SUM_UNITS_RECEIVED) (       
      (SELECT 
        EL_CLIENT_ID||RECORDING_ID||'CT'   AS ID,
        EL_CLIENT_ID                 AS EL_CLIENT_ID, 
        RECORDING_ID                 AS RECORDING_ID, 
        UNIT_TYPE                    AS UNIT_TYPE, 
        'Total'                      AS PHY_DIG_OR_TOTAL, 
        NULL AS CONTROLLED_PERCENTAGE,
        SUM(PERC_ADJ_UNITS_RECEIVED) AS PERC_ADJ_UNITS_RECEIVED,
        SUM(SUM_UNITS_RECEIVED)      AS SUM_UNITS_RECEIVED
    FROM EL_CLIENT_REC_UNITS
    WHERE EL_CLIENT_ID = pRow.ID
    AND UNIT_TYPE = 'Cleared'
    GROUP BY UNIT_TYPE, EL_CLIENT_ID, RECORDING_ID)
    WHERE NOT EXISTS (SELECT );

1 个答案:

答案 0 :(得分:1)

试试这个

INSERT INTO EL_CLIENT_REC_UNITS 
     (ID,
     EL_CLIENT_ID,
     RECORDING_ID,
     UNIT_TYPE,
     PHY_DIG_OR_TOTAL,
     CONTROLLED_PERCENTAGE,
     PERC_ADJ_UNITS_RECEIVED,
     SUM_UNITS_RECEIVED)       
    SELECT * FROM
    (SELECT 
        EL_CLIENT_ID||RECORDING_ID||'CT'   AS ID,
        EL_CLIENT_ID                 AS EL_CLIENT_ID, 
        RECORDING_ID                 AS RECORDING_ID, 
        UNIT_TYPE                    AS UNIT_TYPE, 
        'Total'                      AS PHY_DIG_OR_TOTAL, 
        NULL AS CONTROLLED_PERCENTAGE,
        SUM(PERC_ADJ_UNITS_RECEIVED) AS PERC_ADJ_UNITS_RECEIVED,
        SUM(SUM_UNITS_RECEIVED)      AS SUM_UNITS_RECEIVED
    FROM EL_CLIENT_REC_UNITS
    WHERE EL_CLIENT_ID = pRow.ID
    AND UNIT_TYPE = 'Cleared'
    GROUP BY UNIT_TYPE, EL_CLIENT_ID, RECORDING_ID) INS_VALS
    WHERE NOT EXISTS (SELECT 1 FROM EL_CLIENT_REC_UNITS ELC WHERE ELC.ID =  INS_VALS.ID );