oracle建表设置自增主键
--建表
create table t_student
( s_id number primary key,
name char(10) not null
);
--建序列
create sequence stu_sequence
increment by 1
start with 1
nomaxvalue
nocycle
cache 10;
-- 建触发器
create or replace trigger stu_trigger
before insert on t_student
for each row
declare
nextid number;
begin
IF:new.s_id IS NULL or:new.s_id=0 THEN
select stu_sequence.nextval
into nextid
from sys.dual;
:new.s_id:=nextid;
end if;
end stu_trigger;
注:stu_trigger为触发器名
t_student为表名
s_id为自增长的主键字段名
这样就可以了,插入数据测试:
插一条数据:
insert into t_student (name) values('张三');
插多条数据:
BEGIN
FOR v_i IN 1..10 Loop
INSERT INTO t_student (name) VALUES ('郑成');
END Loop;
COMMIT;
END;
只插主键值:
INSERT INTO t_student(s_id) VALUES (stu_sequence.nextval);