Mysql、Sql Server、Oracle主键自动增加的设置

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

MySql

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

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字段,查询结果为: sql

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

Sql Server

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

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;

注意:在sqlserver中字符串用单引号扩起来,而在mysql中可使用双引号。 ide

查询结果和mysql的同样。 sqlserver

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

之前常常会碰到这样的问题,当咱们删除了一条自增加列为1的记录之后,再次插入的记录自增加列是2了。咱们想在插入一条自增加列为1的记录是作不到 的。今天跟同事讨论的时候发现能够经过设置SET IDENTITY_INSERT <table_name> ON;来取消自增加,等咱们插入完数据之后在关闭这个功能。实验以下: code

use TESTDB2
--step1:建立表
create table customers(
    id int identity primary key not null,
    name varchar(15)
);

--step2:执行插入操做
insert into customers(id,name) values(1,'name1');
--报错:An explicit value for the identity column in table 'customers' can only be specified when a column list is used and IDENTITY_INSERT is ON.

--step3:放开主键列的自增加
SET IDENTITY_INSERT customers ON;

--step4:插入两条记录,主键分别为1和3。插入成功
insert into customers(id,name) values(1,'name1');
insert into customers(id,name) values(3,'name1');

--step5:再次插入一个主键为2的记录。插入成功
insert into customers(id,name) values(2,'name1');

--step6:插入重复主键,
--报错:Violation of PRIMARY KEY constraint 'PK__customer__3213E83F00551192'. Cannot insert duplicate key in object 'dbo.customers'.
insert into customers(id,name) values(3,'name1');

--step7:关闭IDENTITY_INSERT
SET IDENTITY_INSERT customers OFF;

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

Oracle

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

create sequence customer_id_seq increment by 2 start with 1

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

  • 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.nextval, 'name1');
insert into customers values(customer_id_seq.nextval, 'name2');
select id from customers;

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

经过触发器自动添加id字段

从上述插入语句能够发现,若是每次都要插入customer_id_seq.nextval的值会很是累赘与麻烦,所以能够考虑使用触发器来完成这一步工做。

建立触发器trg_customers

create or replace
trigger trg_customers before insert on customers for each row 
begin 
select CUSTOMER_ID_SEQ.nextval into :new.id from dual; 
end;

插入一条记录

insert into customers(name) values('test');

这是咱们会发现这一条记录被插入到数据库中,而且id仍是自增加的。

相关文章
相关标签/搜索