gaodaima.com1、把主键定义为自动增长标识符类型 MySql 在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;
由此可见,一旦把id设为auto_increment类型,mysql数据库会自动按递增的方式为主键赋值。 Sql Server 在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;
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;
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;