在循环语句Oracle9中插入一个id

时间:2018-05-25 08:11:27

标签: sql oracle for-loop plsql unique-constraint

我试图使用for循环在表中插入一堆数据。对于主键,我尝试使用序列,但我得到了一个:

  

ORA-00001:唯一约束(constraint_name)违反了错误。

我的代码如下:

FOR a IN (select * from table a)
LOOP 

    select seq.nextval into id1 from dual;

    insert into table b (primarykey, value1...)

    select (id1, value1...) from table c

end loop

为什么我仍然会遇到一个独特的约束错误?

1 个答案:

答案 0 :(得分:0)

我猜表c包含多行:

FOR a IN (select * from table_a) LOOP
  select seq.nextval into id1 from dual;

  insert into table_b (primarykey, value1...)
  select id1, value1... from table_c;    
  -- the same id1 will be used for many rows 
  -- and cause `UNIQUE` constraint violation

end loop;

我会把它重写为:

INSERT INTO table_b(primarykey, value1...)
SELECT seq.nextval, value1, ...
FROM table_c
WHERE ....;