我有一个包含 5 个字段的表。5列中的一列是PK。我的要求是我需要根据某些列(非重复但不是 PK)获取行,并且对于所有返回的结果,我需要分配新的 PK 并保存。
如果我的表中有 10 条记录。如果我根据某个列获得 10 条记录。我需要为所有 10 条记录分配新的 PK 并保存。最后,表中将有 20 条记录。是否有执行此操作的单个 SQL 查询?
谢谢!
-- 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
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>;
希望能帮助到你...