oracle 主键自动增加

oracle 主键自动增加  

2009-12-11 16:07:00|  分类: 数据库资料|字号 订阅mysql

 
 

这几天搞Oracle,想让表的主键实现自动增加,查网络实现以下:sql

create table simon_example数据库

(网络

  id number(4) not null primary key,oracle

  name varchar2(25)ide

)spa

-- 创建序列:blog

-- Create sequencerem

create sequence SIMON_SEQUENCE                      get

minvalue 1              

maxvalue 999999999999999999999999999 

start with 1

increment by 1

cache 20;

-- 创建触发器

create trigger "simon_trigger" before

insert on simon_example for each row when(new.id is null)

begin

 select simon_sequence.nextval into:new.id from dual;

 end;

-------------------------------------------------------------------------

-------------------------------------------------------------------------

-------------------------------------------------------------------------

一、把主键定义为自动增加标识符类型

在mysql中,若是把表的主键设为auto_increment类型,数据库就会自动为主键赋值。例如:

create table customers(id int auto_increment primary key not null, name varchar(15));

insert into customers(name) values("name1"),("name2");

select id from customers;

以上sql语句先建立了customers表,而后插入两条记录,在插入时仅仅设定了name字段的值。最后查询表中id字段,查询结果为:

id

1

2

因而可知,一旦把id设为auto_increment类型,mysql数据库会自动按递增的方式为主键赋值。

在MS SQLServer中,若是把表的主键设为identity类型,数据库就会自动为主键赋值。例如:

create table customers(id int identity(1,1) primary key not null, name varchar(15));

insert into customers(name) values("name1"),("name2");

select id from customers;

 查询结果和mysql的同样。因而可知,一旦把id设为identity类型,MS SQLServer数据库会自动按递增的方式为主键赋值。identity包含两个参数,第一个参数表示起始值,第二个参数表示增量。

二、从序列中获取自动增加的标识符

在Oracle中,能够为每张表的主键建立一个单独的序列,而后从这个序列中获取自动增长的标识符,把它赋值给主键。例如一下语句建立了一个名为customer_id_seq的序列,这个序列的起始值为1,增量为2。

create sequence customer_id_seq increment by 2 start with 1

一旦定义了customer_id_seq序列,就能够访问序列的curval和nextval属性。

curval:返回序列的当前值

nextval:先增长序列的值,而后返回序列值

如下sql语句先建立了customers表,而后插入两条记录,在插入时设定了id和name字段的值,其中id字段的值来自于customer_id_seq序列。最后查询customers表中的id字段。

create table customers(id int primary key not null, name varchar(15));

insert into customers values(customer_id_seq.curval, "name1"),(customer_id_seq.nextval, "name2");

select id from customers;

若是在oracle中执行以上语句,查询结果为:

id

1

3

----------------------------------------------------------------

----------------------------------------------------------------

----------------------------------------------------------------

学oracle不久,在建表时发现这样一个问题,好比我如今建立一个表:student

create table STUDENT
(
ID NUMBER not null,
NAME VARCHAR2(20) default '男',
SEX VARCHAR2(4),
ADDRESS VARCHAR2(40),
MEMO VARCHAR2(60)
)

如今我想实现每插入一条数据,就让id自动增加1.在SQLSERVER中这个很好实现,但在oracle中我搞了半天,查了下资料发现要用到“序列(sequence)”,“触发器”的知识。

首先,建立一个序列:

create sequence STU
minvalue 1
maxvalue 999999999999
start with 21
increment by 1
cache 20;

而后,给表student建立一个触发器:

create or replace trigger stu_trbefore insert on student for each rowdeclare-- local variables herebeginselect stu.nextval into :new.id from dual;end stu_tr;

相关文章
相关标签/搜索