一、把主键定义为自动增长标识符类型
1.在mysql中,如果把表的主键设为auto_increment类型,数据库就会自动为主键赋值。例如:
create table user(
id int auto_increment primary key not null,
name varchar(15)
)
2.在SQLServer中,如果把表的主键设为identity类型,数据库就会自动为主键赋值。例如:
create table user(
id int identity(1,1) ,
primary key not null,
name varchar(15)
)
一旦把id设为identity类型,SQLServer数据库会自动按递增的方式为主键赋值。identity包含两个参数,第一个参数表示起始值,第二个参数表示增量。
二、从序列中获取自动增长的标识符
在Oracle中,可以为每张表的主键创建一个单独的序列,然后从这个序列中获取自动增加的标识符,把它赋值给主键。例如一下语句创建了一个名为user_id_seq的序列,这个序列的起始值为1,增量为2。
create sequence user_id_seq increment by 2 start with 1
一旦定义了user_id_seq序列,就可以访问序列的curval和nextval属性。
curval:返回序列的当前值
nextval:先增加序列的值,然后返回序列值
以下sql语句先创建了user表,然后插入两条记录,在插入时设定了id和name字段的值,其中id字段的值来自于user_id_seq序列。最后查询user表中的id字段。
create table user(
id int primary key not null,
name varchar(15)
)
insert into user values(user_id_seq.curval, "name1"),(user_id_seq.nextval, "name2")
select id from user
如果在oracle中执行以上语句,查询结果为:
id
1
3