如何通过更新两个字段来插入记录?

时间:2012-07-05 10:38:22

标签: sql oracle

我有一个包含5个字段的表。在5列中,一个是PK。我的需求是我需要根据某些列(非重复但不是PK)获取行,并且对于所有返回的结果,我需要分配新的PK并保存。

如果我的桌子上有10条记录。如果我根据某列获得10条记录。我需要为所有10条记录设置新的PK并保存。最后,表格中将有20条记录。是否有任何单个SQL查询执行此操作?

谢谢!

3 个答案:

答案 0 :(得分:1)

--  create a sequence to manage the primary keys
create sequence key_sequence;

--  i don't know what data you want in your table
create table tempTable (
myKey int primary key,
myValue varchar(12))

--  create four rows of arbitrary data, they will get primary keys of 1,2,3 and 4
insert into tempTable values (key_sequence.nextval, 'eggs')
insert into tempTable values (key_sequence.nextval, 'bacon')
insert into tempTable values (key_sequence.nextval, 'chips')
insert into tempTable values (key_sequence.nextval, 'salad')

--  you can see the 4 rows
select * from tempTable

--  select all four rows (as no where clause) and re-insert them into the table
--  the sequence will take care of allocating new primary keys
insert into tempTable
select  key_sequence.nextval, myValue 
from    tempTable

--  now you can see eight rows in the table
select * from tempTable

答案 1 :(得分:0)

如果col1是PK(对于自动增量柱)

insert into table (col1, col2, col3, col4, col5) 
    select null, col2, col3, col4, col5 
    from table 
    where col2 = 'anyvalue' and more conditions... ;

答案 2 :(得分:0)

我不确定我是否理解你,但这会做你需要的吗?

由于你没有提供太多细节,你必须填补空白!

INSERT INTO <table> (
   pk_col,
   col2,
   col3,
   col4,
   col5
)
   SELECT <new_pk>,
          col2,
          col3,
          col4,
          col5
     FROM <table>
    WHERE <your search criteria>;

希望它有所帮助...

相关问题