日期:2014-05-16  浏览次数:20759 次

Mysql、SqlServer、Oracle主键自动增长的设置

1、把主键定义为自动增长标识符类型

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

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

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

?

2、在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");

?

identity包含两个参数,第一个参数表示起始值,第二个参数表示增量。


3、Oracle列中获取自动增长的标识符

在Oracle中,可以为每张表的主键创建一个单独的序列,然后从这个序列中获取自动增加的标识符,把它赋值给主键。

例如一下语句创建了一个名为customer_id_seq的序列,这个序列的起始值为1,增量为2。

方法一、

create sequence customer_id_seq increment by 2 start with 1

?

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

curval:返回序列的当前值