db2使用insert语句设置递增值

时间:2014-10-28 09:15:36

标签: sql database insert db2 increment

我有两张桌子:

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



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

我需要向MYTABLE1插入10,000行,其中ID = MY_ID Col1 = 50每次插入行时,蚁群Col2递增,因此MYTABLE1看起来像这样:

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

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

但我仍然无法弄清楚如何从MYTABLE2加载所有ID

请帮忙, 谢谢你的回答。

1 个答案:

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