SQL Server数据库操作(二)

一、添加约束的语法

alter table 表名 add constraint 约束名 约束类型 具体的约束说明

use studentmanagedb
go
--添加约束,创建主键约束
if exists(select * from sysobjects where name='pk_StudentId')
alter table Students drop constraint pk_StudentId

alter table Students add constraint pk_StudentId primary key(StudentId)

--添加约束,创建唯一约束
if exists(select * from sysobjects where name='uq_StudentIdNo')
alter table Students drop constraint uq_StudentIdNo

alter table Students add constraint uq_StudentIdNo unique(StudentIdNo)
--添加约束,创建检查约束
if exists(select * from sysobjects where name='ck_Age')
alter table Students drop constraint ck_Age

alter table Students add constraint ck_Age check(Age between 18 and 26)

if exists(select * from sysobjects where name='ck_PhoneNumber')
alter table Students drop constraint ck_PhoneNumber

alter table Students add constraint ck_PhoneNumber check(len(PhoneNumber)=11)
--创建外键约束
if exists(select * from sysobjects where name='fk_ClassId')
alter table Students drop constraint fk_ClassId

alter table Students add constraint fk_ClassId foreign key(ClassId) references StudentClass(ClassId)

实体完整性

  a.能够唯一标识表中的每一条记录。

  b.实现方式:主键、唯一键、IDENTITY属性。

域完整性

  a.表中特定列数据的有效性,确保不会输入无效的值。

  b.实现方式:数据类型限制、缺省值、非空值。

引用完整性

  a.维护表间数据的有效性、完整性。

  b.实现方式:建立外键,关联另一表的主键。

主键的选择

  a.最少性原则:尽量选择单个键作为主键。

  b.稳定性原则:尽量选择数值更新少的列作为主键。

外键使用

  a.要求数据类型、数据长度必须与对应的主键表字段完全一致。

  b.添加数据时,要首先添加主键表,在添加外键表。

  c.删除数据时,要首先删除外键表数据,在删除主键表数据。

完整数据库创建步骤

  建库---->建表---->主键约束---->域完整性约束---->外键约束

插入数据的过程

  验证主键、主外键关系、检查约束……---->插入成功

posted @ 2017-02-25 10:24  行走的影子  阅读(304)  评论(0编辑  收藏  举报