3.primary key 约束
描述:primary key约束唯一标识数据库表中的每一条记录。主键必须包含唯一的值。主键列不能包含null值。每个表都应该有一个主键,并且每个表只能有一个主键。
新建表
语法:
数据库:Mysql:
create table persons
(
id int not null,
name varcher(255) not null,
primary key(id)
)
数据库:sql Server /Oracle/MS Access:
create table persons
(
id int not null primary key,
name varcher(255)
)
如果需要命名primary key约束,以及为多个列定义primary key约束(组合主键),请使用下面的sql语法:
数据库:MySQL/SQL Server/Oracle/Ms Access:
create table persons
(
id int not null,
name varchar(225) not null,
address varchar(225) ,
constraint pk_personID primary key (id,name)
)
---pk_personID是组合主键的名称
表已经存在
语法:
数据库:MySQL/SQL Server/Oracle/MS Access:
alter table persons
add primary key (id)
如果需要命名primary key约束,以及为多个定义primary key约束,请使用下面的sql语法:
数据库:MySQL/SQL Server/Oracle/MS Access:
alter table persons
add constraint pk_personID primary key (id,name)
注意:如果你使用alter table语句添加主键,必须把主键列声明为不包含null值(在表首次创建时)。
撤销primary key约束
如果需要撤销primary key约束,请使用下面的sql
数据库:MySQL:
alter table persons
drop primary key
数据库:SQL Server /Oracle/MS Access:
alter table persons
drop constraint pk_personID
--pk_personID是primary key约束名