db2通过不同表中的select值插入

时间:2011-11-23 08:16:27

标签: insert db2

我正在尝试插入1个表中,其中一个字段是在插入时需要增加的运行,所以我创建插入sql如下

 INSERT INTO ICGR1100(C_IST, NUM_RIF, C_ORO, NUM_SER, TMSP_CAR, 
                      C_AG_CAR, C_MATR_CAR, C_TP_MAG, DT_RIC, C_FORN, 
                      IMP_PREM, DT_PAGM_PREM, IMP_ACQ, DT_ACQ, IMP_VEND, 
                      DT_VEND, F_GRTS, TMSP_ULT_AGG, C_MATR_ULT_AGG) 
 VALUES('01', (SELECT MAX_NUM_RIF 
                 FROM FINAL TABLE(UPDATE ICGR1005 
                 SET MAX_NUM_RIF = CAST(CAST((CAST(MAX_NUM_RIF AS DECIMAL(16))+1)
                                   AS DECIMAL(16)) AS CHAR(16)) WHERE C_IST='01')), 
                 '005', '0000000000357209', '2011-11-23 17:00:00.000', 
                 '90109', 'Gold', '03', '20111122', '001', 17900, '20111122', 
                 1667500, '20111122', 1795395, '20111122', '0', 
                 '2011-11-23 17:00:00.000', 'Gold')

但是得到错误 DB2 SQL错误:

SQLCODE=-20165, SQLSTATE=428FL, SQLERRMC=null, DRIVER=3.50.152

消息:

An SQL data change statement within a FROM  clause is not allowed in the context in which it was specified.. `SQLCODE=-20165, SQLSTATE=428FL, DRIVER=3.50.152` 

任何人都可以建议我

提前致谢

2 个答案:

答案 0 :(得分:0)

您可以尝试以下操作:

INSERT INTO ICGR1100 (
    C_IST, NUM_RIF, C_ORO, NUM_SER, TMSP_CAR, C_AG_CAR, C_MATR_CAR, C_TP_MAG, DT_RIC,     C_FORN, IMP_PREM, DT_PAGM_PREM, MP_ACQ, DT_ACQ, IMP_VEND, DT_VEND, F_GRTS, TMSP_ULT_AGG, C_MATR_ULT_AGG
)
SELECT
    '01', MAX_NUM_RIF, '005', '0000000000357209', '2011-11-23 17:00:00.000', '90109', 'Gold', '03', '20111122', '001', 17900, '20111122', 1667500, '20111122', 1795395, '20111122', '0', '2011-11-23 17:00:00.000', 'Gold'
FROM FINAL TABLE (
    UPDATE ICGR1005
    SET
        MAX_NUM_RIF = CAST(CAST((CAST(MAX_NUM_RIF AS DECIMAL(16))+1) AS DECIMAL(16)) AS CHAR(16))
    WHERE C_IST = '01'
)

如果这不起作用,我建议发布相关的CREATE和INSERT语句,以便我们可以在本地运行测试。

答案 1 :(得分:0)

好的简单解决方案,我只是先运行增量,然后插入如下:

UPDATE ICGR1005 SET MAX_NUM_RIF=CAST(CAST((CAST(MAX_NUM_RIF AS DECIMAL(16))+1) AS DECIMAL(16)) AS CHAR(16)) WHERE C_IST='01';
INSERT INTO ICGR1100(C_IST, NUM_RIF, C_ORO, NUM_SER, TMSP_CAR, C_AG_CAR, C_MATR_CAR, C_TP_MAG, DT_RIC, C_FORN, IMP_PREM, DT_PAGM_PREM, IMP_ACQ, DT_ACQ, IMP_VEND, DT_VEND, F_GRTS, TMSP_ULT_AGG, C_MATR_ULT_AGG) 
VALUES('01', (SELECT MAX_NUM_RIF FROM ICGR1005), '005', '0000000000357209', '2011-11-23 17:00:00.000', '90109', 'Gold', '03', '20111122', '001', 17900, '20111122', 1729000, '20111122', 1869138, '20111122', '0', '2011-11-23 17:00:00.000', 'Gold');