您的位置:首页 > 数据库 > Oracle

Oracle 创建自增列

2015-11-19 09:54 435 查看
类似SqlServer中的标识列 identity,Oracle实现同样的效果有点小复杂额,如下:

--1.创建表
create table Student(
ID integer not null primary key,
Name varchar2(40) not null,
Sex integer,
Address varchar2(100)
)
tablespace MyTest_Data;--指明表空间

--2.创建序列
create sequence SEQ_StuID
minvalue 1
start with 1
increment by 1
nomaxvalue
nocache;

--3.创建触发器
create OR REPLACE TRIGGER Trigger_StuID
BEFORE insert
ON Student
FOR EACH ROW
BEGIN
if inserting then
if :NEW."ID" is null then
select SEQ_StuID.nextval into :NEW."ID" from dual;
end if;
end if;
END;

--4.激活触发器
alter table "admin"."Student" --用户.表名
enable all triggers;

--5.插入数据
insert into Student(NAME,SEX,ADDRESS) values('张三',1,'第七街区');

--可以使用【序列名.newxtval】查看下一个要使用的序列号
--注意:以下语句执行一次会按指定的增量增加
select SEQ_StuID.nextval from dual
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: