一.主键约束
1.在创建表时创建主键约束
use xsgl
go
create table xs
( 学号 numicer not null constraint pk_xsh primary key,
姓名 nvarchar(4) not null
)
2.向已有表中添加主键约束
use xsgl
go
add constraint pk_xsh primart key(学号)
3.删除主键约束
alter table xs
drop constraint pk_xsh
二.唯一键约束
1.在创建表时创建唯一键约束
use xsgl
create table xs
( 学号 numicer not null constraint pk_xsh primary key,
姓名 nvarchar(4) not null constraint ix_xsh unique
)
2.向已有表中添加唯一键约束
use xsgl
go
add constraint ix_xsh unique(姓名)
3.删除唯一键约束
use xsgl
go
drop constraint ix_xsh
三.检查约束
1.在创建表时创建检查约束
use xsgl
go
create table xs
(学号 numicer not null constraint pk_xsh primary key,
姓名 nvarchar(4) not null constraint ix_xsh unique,
电话 char(8) null constraint ik_xsh check ([电话] like '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]')
)
2.向已有表中添加检查约束
use xsgl
go
alter table xs
with nocheck //不检查现有数据的检查约束,若没有此语句,则对已有的数据也进行检查
add constraint ik_xsh
check ([电话] like '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]')
go
3.使check检查失效
alter table xs
nochexk constraint ik_xsh
4.使chexk检查生效
alter table xs
check constraint ik_xsh
5.删除检查约束
alter table xs
drop constraint ik_xsh
go
四.默认值约束
1.在创建表时创建默认值约束
use xsgl
go
create table xs
(
专业 nvarchar(8) null default '电子商务'
)
2.向已有表中添加默认值约束
use xsgl
go
alter table xs
add constraint ih_xsh default '电子商务'for 专业
3.删除默认值约束
use xsgl
go
alter table xs
drop constraint ih_xsh
go
五.外键约束
1.在创建表时创建外键约束
(把课程表中的学号创建为外键,其主键为xs表中的学号)
use xsgl
go
create table cj
(学号 numicer not null constraint id_xsh foreign key
references xs(学号)
)
go
2.向已有表中添加外键约束
(把课程表中的学号创建为外键,其主键为xs表中的学号)
use xgsl
go
alter table cj
add constraint id_xsh foreign key(学号)
references xs(学号)
3.删除外键约束
use xgsl
go
alter table cj
drop constraint id_xsh
go
六.默认值
1.创建默认值
use xshgl
go
create default df_学时数 as 60
go
2.绑定默认值
use xsgl
go
exec sp_bindefault 'df_学时数','kc.学时数'
go
3.解绑默认值
use xsgl
go
exec sp_unbindefault 'kc.学时数'
go
4.删除默认值
use xsgl
go
exec sp_unbindefault 'kc.学时数'
go
drop default df_学时数
go