当前位置:首页 > 数据库 > Sqlserver

SQL Server数据库操作(二)

一、添加约束的语法

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

            use
             studentmanagedb

            go
            --
            添加约束,创建主键约束
            if
            exists(select*from sysobjects where name=pk_StudentId)
altertable Students dropconstraint pk_StudentId

altertable Students addconstraint pk_StudentId primarykey(StudentId)

--添加约束,创建唯一约束ifexists(select*from sysobjects where name=uq_StudentIdNo)
altertable Students dropconstraint uq_StudentIdNo

altertable Students addconstraint uq_StudentIdNo unique(StudentIdNo)
            --
            添加约束,创建检查约束
            if
            exists(select*from sysobjects where name=ck_Age)
altertable Students dropconstraint ck_Age

altertable Students addconstraint ck_Age check(Age between18and26)

ifexists(select*from sysobjects where name=ck_PhoneNumber)
altertable Students dropconstraint ck_PhoneNumber

altertable Students addconstraint ck_PhoneNumber check(len(PhoneNumber)=11)
            --
            创建外键约束
            if
            exists(select*from sysobjects where name=fk_ClassId)
altertable Students dropconstraint fk_ClassId

altertable Students addconstraint fk_ClassId foreignkey(ClassId) references StudentClass(ClassId)

实体完整性

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

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

域完整性

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

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

引用完整性

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

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

主键的选择

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

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

外键使用

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

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

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

完整数据库创建步骤

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

插入数据的过程

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

原文:http://www.cnblogs.com/sgmcumt/p/6441064.html


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!