【问题标题】:db2 set incrementing values using insert statementdb2 使用插入语句设置递增值
【发布时间】:2014-10-28 09:15:36
【问题描述】:

我有两张桌子:

MYTABLE1
ID   |Col1|Col2      |
--------------------- ....
64  |  50 |   7000   |



MYTABLE2
MY_ID |
-------
  64  | 
  87  |

我需要在 MYTABLE1 中插入大约 10,000 行,其中 ID=MY_ID Col1=50 ant Col2 每次插入行时都会递增,因此 MYTABLE1 看起来像这样:

ID   |Col1|Col2      |
--------------------- ....
64  |  50 |   7000   |
87  |  50 |   7001   |

我在这里找到了类似的解决方案:insert thousands of rows in DB2

但我仍然不知道如何从 MYTABLE2 加载所有 ID

请帮忙, 谢谢你的回答。

【问题讨论】:

    标签: sql database insert db2 increment


    【解决方案1】:
    insert into MYTABLE1 (id, col1, col2)
    select my_id, 50 col1, col2 + row_number() over(order by my_id) from
    (
        select MY_ID, m.col2
        from MYTABLE2 t2, (select max(col2) as col2 from MYTABLE1) m
    ) t2
    -- if you don't want to insert IDs which already exist in MYTABLE1
    where not exists (select 1 from MYTABLE1 t1 where t1.ID = t2.MY_ID);
    

    【讨论】:

    • Error: DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=M.COL2, DRIVER=3.63.75 SQLState: 42703 ErrorCode: -206
    • @JulioBordeaux 我在此语句中添加了 AS:“select max(col2) as col2”。这是我唯一能想到的。
    • 我认为可能是“m”
    • @JulioBordeaux 这只是一个子查询别名
    • 哇,当我尝试(select max(col2) as col2 from MYTABLE1) AS m 时,它成功了。非常感谢,伙计! :)
    猜你喜欢
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    • 2020-11-07
    • 2010-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多