1、方式一:使用序列和触发器
2、方式二:仅使用序列
- SQL> CREATE SEQUENCE test_sequence2
- 2 increment by 1 -- 每次递增1
- 3 start with 1 -- 从1开始
- 4 nomaxvalue -- 没有最大值
- 5 minvalue 1 -- 最小值=1
- 6 NOCYCLE; -- 不循环
- Sequence created.
- SQL> CREATE TABLE test_create_tab2 (
- 2 id INT,
- 3 val VARCHAR(10),
- 4 PRIMARY KEY (id)
- 5 );
- Table created.
- SQL> CREATE OR REPLACE TRIGGER BeforeTestCreate2Insert
- 2 BEFORE INSERT ON test_create_tab2
- 3 FOR EACH ROW
- 4 BEGIN
- 5 SELECT test_sequence2.nextval INTO :new.id FROM dual;
- 6 END;
- 7 /
- Trigger created.
- SQL> INSERT INTO test_create_tab2(val) VALUES ('NO id');
- 1 row created.
- SQL> INSERT INTO test_create_tab2(id, val) VALUES (1, 'id no use');
- 1 row created.
- SQL> SELECT * FROM test_create_tab2;
- ID VAL
- ---------- --------------------
- 1 NO id
- 2 id no use
2、方式二:仅使用序列
- [TEST1@orcl#27-12月-10] SQL>create table y_one(id number);
- 表已创建。
- [TEST1@orcl#27-12月-10] SQL>create sequence y_seq start with 1 increment by 1 nomaxvalue nocycle
- 2 ;
- 序列已创建。
- [TEST1@orcl#27-12月-10] SQL>insert into y_one values(y_seq.nextval);
- 已创建 1 行。
- [TEST1@orcl#27-12月-10] SQL>insert into y_one values(y_seq.nextval);
- 已创建 1 行。
- [TEST1@orcl#27-12月-10] SQL>insert into y_one values(y_seq.nextval);
- 已创建 1 行。
- [TEST1@orcl#27-12月-10] SQL>commit;
- 提交完成。
- [TEST1@orcl#27-12月-10] SQL>select * from y_one;
- ID
- ----------
- 1
- 2
- 3
1、创建表
create table note(
id number(20) NOT NULL primary key,/*主键,自动增加*/ name varchar2(20));
2、创建自动增长序列
Create Sequence addAuto_Sequence
Increment by 1 -- 每次加几个
start with 1 -- 从1开始计数
nomaxvalue -- 不设置最大值,设置最大值:maxvalue 9999
nocycle -- 一直累加,不循环
cache 10;
3、创建触发器
Create trigger addAuto before
insert on note(表名) for each row /*对每一行都检测是否触发*/
begin
select addAuto_Sequence.nextval into:New.id from dual;
end;
4、提交 commit;
5、测试 insert into note(name) values(‘lisi’);