约束

create table autor ---作者信息表
(
    AId varchar(20),
    AName varchar(20),
    Aage int
)

--------------

非空约束

eg:把AId的值改为非空

alter table autor alter column  AId varchar(20) not null

在这里要注意 null与' '空值的区别

----------------

唯一约束

eg: 把AId字段设置成唯一的两种SQL:

create unique index  U_AId on autor (AId )
alter table  autor add unique (AId)

也可以直接在创建表的时候,在Aid字段后面加上Unique

在这里要注意 '唯一约束'与'复合唯一约束的区别'

复合唯一约束语法; constraint 约束名 unique (字段1 , 字段2,....)

---------------

check约束

eg: 限制Aage必须大于0

alter table autor add Check(Aage>0)

check约束中可以使用函数

eg: create table A (name varchar(20) check(len(name)>2),

   age int check(age>0)

---------------

主键约束

主键的字段的值必须是唯一的,且不能为空。主键是unique与非空约束的集合,一个表只能有一个主键

alter table autor add primary key (AId)---添加

alter tabel autor drop  constraint  AId ---删除

--------------外键约束

语法:foreign key (字段名) references 目标表名 (被关联的字段 )

 alter table autor add foreign key (AId) references autor ( A )

原文地址:https://www.cnblogs.com/lucky9/p/6278559.html