2012-10-02 132 views
0

可能重複:
oracle insert if row not existsOracle PLSQL僅在不存在時插入。

我使用下面的查詢來計算總的一些數據,但是,我想插入如果ID不只有被執行首先存在於EL_CLIENT_REC_UNITS中。任何人都可以看到這樣做的方式?

 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); 
+0

或http://stackoverflow.com/questions/10824764/oracle-insert-if-not-exists-statement,或http://stackoverflow.com/questions/8185250/sql-insert-if-not-exist或http://stackoverflow.com/questions/3841441/insert-if-row-dont-exist ...以及更多 – Ben

回答

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