失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > oracle自增插入数据 oracle实现插入数据时主键自增

oracle自增插入数据 oracle实现插入数据时主键自增

时间:2019-04-29 01:21:48

相关推荐

oracle自增插入数据 oracle实现插入数据时主键自增

在看ORACLE_PL/SQL实例精解的时候用到了student表,需要自己创建。

1 首先是建表语句

create table student (

student_id number(8) not null primary key, --主键列

first_name varchar2(50), -- 名字

last_name varchar2(50) -- 姓

);

2 创建自增序列

create sequence seq_student

minvalue 1 --最小值

nomaxvalue --最大值

start with 1 --起始值

increment by 1 --增长基数

nocycle --不循环,一直增加

nocache ; -- 不使用缓存

到这里其实就可以使用了,只是在插入的时候必须要自己调用,像这样

insert into student(student_id,first_name,last_name) values(seq_student.nextval,'','');

为了可以不关注主键列,创建一个触发器。

3 创建触发器(插入数据时触发)

create trigger tri_student_ins

before insert on student for each row when (new.student_id is null)

begin

select seq_student.nextval into:new.student_id from dual;

end;

这样就可以插入数据了

insert into student(first_name,last_name) values('','');

4 写一个pl/sql代码块,批量插入数据

declare

i number := 1;

v_first_name varchar2(50);

v_last_name varchar2(50);

begin

for i in 1 .. 200

loop

v_first_name := '' || to_char(i);

v_last_name := '' || to_char(i);

insert into student(first_name,last_name) values(v_first_name,v_last_name);

commit;

end loop;

end;

如果觉得《oracle自增插入数据 oracle实现插入数据时主键自增》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。