如何通过更新两个字段来插入记录?
问题描述:
我有一个表有5个字段。 5列之一是PK。我的需求是我需要基于某些列(非重复但不是PK)获得行,对于所有返回的结果,我需要分配新的PK并保存。如何通过更新两个字段来插入记录?
如果我在我的表中有10条记录。如果我根据某一列获得10条记录。我需要为所有10条记录分配新的PK并保存。最后在表中会有20条记录。有没有执行此操作的任何单个SQL查询?
谢谢!
答
IF COL1是PK(自动增量列)
insert into table (col1, col2, col3, col4, col5)
select null, col2, col3, col4, col5
from table
where col2 = 'anyvalue' and more conditions... ;
答
我不知道如果我理解正确的话,你但这样做你需要什么?
由于您没有给出太多细节,因此您必须填写空格!
INSERT INTO <table> (
pk_col,
col2,
col3,
col4,
col5
)
SELECT <new_pk>,
col2,
col3,
col4,
col5
FROM <table>
WHERE <your search criteria>;
希望它可以帮助...
答
-- 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
YS是可以的,但是你需要证明UR PK决策逻辑和表模式 – Zia 2012-07-05 10:43:01
如果确定有没有冲突,你可以使用序列并使用sequence_name.NEXTVAL生成一个PK – 2012-07-05 10:46:01