在Oracle数据库中使用触发器和序列实现主键自增

2017-01-06 10:08:18来源:oschina作者:月光-云海人点击



#### 一、创建序列
``` sql
create sequence SEQ_USER_ID
minvalue 1
maxvalue 99999999999
start with 1
increment by 1;
```
#### 二、创建数据库表
```
create table MS_USER(
user_id number(11) not null primary key,
mobile_phone varchar2(16) not null,
user_name varchar2(32) not null
);
-- 增加数据库表备注和表字段的备注信息
comment on table MS_USER is '用户信息表';
comment on column MS_USER.user_id is '用户ID';
comment on column MS_USER.mobile_phone is '手机号码';
comment on column MS_USER.user_name is '用户名称';
```
#### 三、创建触发器
```
create or replace trigger MS_USER_TRIGGER
before insert on MS_USER
for each row
begin
select SEQ_USER_ID.nextval into :new.user_id from dual;
end ;
/
```
#### 四、测试
**插入记录:**
```
insert into MS_USER(mobile_phone, user_name) values('12345678901', 'Kevin');
```
**查询记录:**
```
select * from ms_user;
```

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台