一、创建表

--创建student表
create table student(
	id number not null,  --学生id
	name varchar2(20) not null  --学生姓名
);

二、创建序列

create sequence student_id_seq;  --创建序列

三、测试(向表中添加数据)

insert into student values (student_id_seq.nextval,'张三');
insert into student values (student_id_seq.nextval,'李四');
select * from student;  --查询表

 四、使用触发器创建自增字段

create or replace trigger student_auto_incr
before insert on student  --before:执行DML等操作之前触发
for each row  --行级触发器
begin 
	select student_id_seq.nextval into :new.id from dual;
end;
/

触发时机:

before:能够防止某些错误操作发生而便于回滚或实现某些业务规则,适用于实现自增字段;

after:在DML等操作发生之后发生,这种方式便于记录该操作或做某些事后处理信息;

instead of:触发器为替代触发器。

 五、测试

insert into student(name) values ('张三');
insert into student (name) values ('李四');
select * from student;
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐