【转】SQL Server的几种约束

SQL Server中有五种约束类型,分别是 PRIMARY KEY约束、FOREIGN KEY约束、UNIQUE约束、DEFAULT约束、和CHECK约束

使用SQL语句在初次建立数据表时,同时增加约束的方法非常简单:
create table 表名
(列名 列的属性 约束名
    [,...n] )即可,可建立的约束包括primary key 、foreign key、null/not null、check、default等
例如create table student
( stu_no char(6) primary key,
   stu_name char(10) not null,
   stu_sex char(2) check(stu_sex='男' or stu_sex='女'),      /*约束此列的值只能输入“男”或“女”值*/
   stu_nation char(10) default '汉族',
    )
create table grade
( stu_no char(6) foreign key (stu_no) references student(stu_no),     /*此为定义外键约束*/
   subject_no int,
   grade decimal(4,1) check(grade>=0 or grade <=100)                 /*约束成绩取值范围在0-100分之间*/

但是若建立好数据表之后,想要再往列增加约束或修改约束,则格式根据约束的不同各有不同:
use xscj
go
create table abc
(s_no char(10),
s_name char(10),
s_sex char(2),
   s_nation char(16)
)                 /*以上为建立一个没有任何约束的新数据表*/                     
go
alter table abc
alter column s_no char(10) not null             
go
alter table abc
add   primary key (s_no)          /* 以上为给表的s_no列加上primary key 约束*/
go
alter table abc
add check(s_sex='男'or s_sex='女')     /*给x_sex列加check约束*/
go
alter table abc
add default '汉族'   for   s_nation        /*加default约束时格式和其他的有所不同*/
go
但如果是建立表时已经给列建立了某种约束,需要修改其约束的话,则需要先删除掉原有约束,然后再增加新约束,至于删除约束的命令格式为:alter table 表名 drop constraint 约束名
此处的约束名由于建立约束时给省略了,所以需通过“sp_helpconstraint 表名”命令查看到列上对应的constraint_name(即约束名)

总结!!!

create table test /*创建test表*/

( test_no char(6) primary key, /*新增字段test_no 并设置为主键*/
   test_name char(10) not null, /*创建字段test_name 并设置不能空*/
   test_sex char(2) check(test_sex='男' or test_sex='女'),      /*约束此列的值只能输入“男”或“女”值 感觉有点像 vb 哈哈*/
   test_nation char(10) default '汉族', /*创建字段test_nation 并设置默认值为汉族*/
)

另外:再约束中 也可以有 and 这个连接字。
如 check(test_age>0 and test_age<=150) #年龄再0到150之间
当然还可以用 in 这个
如 check(test_sex in ('男','女','中性')) #性别是 男 女 或中性

附上:
删除约束
alter table 表名 drop constraint 约束名
增加约束
alter table abc
add check(test_sex='男'or test_sex='女')     /*给test_sex列加check约束*/

原文地址:https://www.cnblogs.com/xiaolinshushu/p/3256110.html