Oracle多个插入,不同的ID

时间:2010-12-03 09:11:48

标签: oracle insert

我想将一些数据从一个表移动到另一个表。我编写了一个我认为可行的查询,但在目标表中,有一个包含id的列。我希望我插入的每一行都有一个不同的连续ID。这是一个简化的例子:

Table1
Name Telephone Actie
Peter 123456 Y
Michael 111111 Y
George 1234445 N

Table2
Id Name Likes
1 Peter Books
2 Michael Books

我写的查询:

insert all into table2 (name, likes)
select all.name name, 'Books' likes, from (select o.name
  from table1 o where o.active='Y') all;

有没有办法生成连续的ID并使用“insert all into”查询?一个序列?如果它可以用序列制作......有没有任何方法可以在没有序列的情况下完成它?

谢谢和问候!

2 个答案:

答案 0 :(得分:2)

您可以使用ROWNUM:

insert into table2 (id, name, likes)
select ROWNUM, all.name name, 'Books' likes from (select o.name
  from table1 o where o.active='Y') all;

我不确定为什么你有子查询(也许你真正的查询更复杂?)你可以写:

insert into table2 (id, name, likes)
select ROWNUM, o.name, 'Books' likes 
  from table1 o where o.active='Y';

答案 1 :(得分:2)

在Oracle中生成id的正确方法是使用序列。

create sequence seq_table2_id nocache;

然后插入调用seq_table2_id.nextval。

insert into table2 (id, name, likes)
select seq_table2_id.nextval
,      o.name
,      'Books'
from   table1 o
where  o.active = 'Y'

我个人使用触发器自动调用插入序列,但有些人不喜欢使用触发器。