约束

T-sql有两种方式:

1.在创建表的时候直接添加约束

create table 学生表

(

ID int primary key  identity(1,1),  --主键 ,自增列

sex varchar(50) default('男'),--默认值

age int check(age>18 and age<25),

toClassId int references classtable(classid)--外键约束

)

 

注:classTable 班级表 classid 班级编号 toclassid 所属班级编号

 

2.

alter table 表名 add constraint pk_约束名 prmary key(列名) --主键

alter table 表名 add constraint ck_约束名 check(条件) --检查约束

alter table 表名 add constraint df_约束名 default (值) for 列名 --默认约束

alter table 表名 add constraint fk_外键名 foreign key (约束列)  reforences  关系表(关系列)--外键约束

 

 

注:根据需求使用约束

 

posted @ 2018-04-10 22:34  newRohLzy  阅读(81)  评论(0编辑  收藏  举报