[英]Trying to insert some data and an incrementing number as id (oracle db)
I'm trying to insert data in my table1 that looks like this : id, value1, value2.. 我正在尝试在表1中插入如下数据:id,value1,value2。
id being the primary key. id是主键。 I have an insert statement looking like this:
我有一个插入语句,看起来像这样:
insert into table1 (id,value1,value2..)
select ([*],value1, value2 ..)
from table2
Now I want to have an incrementing number starting at 1 to be inserted into id from table1. 现在,我想要一个从1开始的递增数字,将其插入到table1的id中。 What do I need to write into * to make this work?
要使此工作有效,我需要写些什么?
In Oracle 12C, you can define id
as a generated column. 在Oracle 12C中,可以将
id
定义为生成的列。 Here is an article on the subject. 这是有关该主题的文章。
In earlier versions of Oracle, I define a sequence: 在早期版本的Oracle中,我定义了一个序列:
create sequence table1_sequence;
You can use it directly in the insert
: 您可以在
insert
直接使用它:
insert into table1 (id,value1,value2..)
select table1_sequence.nextval, value1, value2 ..
from table2 ;
Or, what I normally do, is create an insert
trigger to set the id
automatically for any insert. 或者,我通常要做的是创建一个
insert
触发器,以自动为任何插入设置id
。
If you are only loading the table once, you can do the quicker-and-dirtier: 如果只加载一次表,则可以更快更快捷:
insert into table1 (id,value1,value2..)
select row_number() over (order by ?), value1, value2 ..
from table2 ;
The order by
is in case you want the ids in a particular order. 在
order by
是如果你想在一个特定的顺序的ID。
Or, you can simply use: 或者,您可以简单地使用:
insert into table1 (id,value1,value2..)
select rownum, value1, value2 ..
from table2 ;
There is no such thing as "auto_increment" or "identity" columns in Oracle as of Oracle 11g.
从Oracle 11g开始,Oracle中没有“ auto_increment”或“ identity”列。 However, you can model it easily with a sequence and a trigger:
但是,您可以使用序列和触发器轻松对其进行建模:
CREATE SEQUENCE id_seq START WITH 1;
Trigger definition: 触发定义:
CREATE OR REPLACE TRIGGER table1_tir
BEFORE INSERT ON table1
FOR EACH ROW
BEGIN
SELECT id_seq.NEXTVAL
INTO :new.id
FROM dual;
END;
IDENTITY column is available on Oracle 12c:
IDENTITY列在Oracle 12c上可用:
create table table1(
id NUMBER GENERATED by default on null as IDENTITY,
value1 VARCHAR2(10),
value2 VARCHAR2(10)
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.