SQL约束简介.docVIP

  • 6
  • 0
  • 约7.9千字
  • 约 9页
  • 2017-02-01 发布于重庆
  • 举报
SQL约束简介

约束简介(一) 一:类型 约束的类型一共分三种 域约束:涉及一个或多个列,(限制某一列的数据大于0) 实体约束:相同的值不能存在于其他的行中 引用完整性约束:一个表中的一个列与某个表中的另一个列的值匹配 二:命名 约束是可以命名的,一般这样命名: pk_customer_***,pk代表主键 customer代表主键所在的表后面是你自己定义的(要确保整个名称的唯一性) 三:主键约束 主键约束:一般就是id, 一个表中最多有一个主键: 例子1 use accounting create table employee ( id int identity not null, firstname varchar(20) not null ) 例子2 use accounting alter table employee add constraint pk_employeeid primary key (id) 四:外键约束 外键约束用在确保数据完整性和两个表之间的关系上,先看例子: create table orders ( id int identity not null primary key, customerid int not null foreign key references customer(id), orderdate smalldatetime not null, eid int not null ) 注意:这个表的外键必须是另一个表的主键!在现有表上添加外键如下: alter table orders add constraint fk_employee_creator_order foreign key (eid) references employee(employeeid) 使用表自引用,表内至少要有一行数据才可以这么做。 alter table employee add constraint fk_employee_has_manager foreign key (managerid) references employee(employeeid) 创建表的时候做表自引用,就可以忽略 foreign key 语句。 表自引用的外键列 必须允许为null 要不是不允许插入的(避免对最初行的需要) 一个表与另一个表有约束,这个表是不能被删除的。 级联操作 先看例子 create table orderdetails ( orderid int not null , id int not null , description varchar(123) not null, --设置主键 constraint pkOrderdetails primary key (orderid,id), --设置外键,级联操作 constraint fkOrderContainsDetails foreign key (orderid) references orders(orderid) on update no action on delete cacade ) on delete cacade 当删除父记录时 同时删除该记录 也就是当删除orders表中的一条记录, 与之相关的orderdetails表中的记录也将被删除 级联的深度是没有限制的,但是每个外键都必须设置on delete cacade no action是可选的 五:unique约束unique约束与主键约束类似,同样也是要求指定的列有唯一的值 但是一个表中可以有多个unique约束的列,同时这个列允许存在null值。(最多有一个null值) 看例子: create table shippers ( id int indentity not null primery key, zip varchar(10) not null , phoneno varchar(14) not null unique ) 例子二: alter table employee add constraint ak_employeeSSN unique(ssn) 六:check约束check不局限于一个特定的列,可以约束一个列,也可以通过某个列来约束另一个列 定义check约束使用的规则与where子句中的基本一样 下面我写几个 between 1 and 12 like [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9][0-9] in (ups,fed ex,usps) price =0 shipdate = orderdate 看例子: alter table customers add constraint

文档评论(0)

1亿VIP精品文档

相关文档