首页 > 数据库技术 > 详细

数据库五大约束使用方法

时间:2019-11-11 11:15:11      阅读:101      评论:0      收藏:0      [点我收藏+]

https://www.cnblogs.com/Qos8/p/mssql.html

数据库中的五种约束及其添加方法
五大约束

  1. —-主键约束 (Primay Key Constraint)    唯一性,非空性
  2. —-唯一约束 (Unique Constraint)            唯一性,可以空,但只能有一个
  3. —-检查约束 (Check Constraint))            对该列数据的范围、格式的限制(如:年龄、性别等)
  4. —-默认约束 (Default Constraint)            该数据的默认值
  5. —-外键约束 (Foreign Key Constraint)     需要建立两表间的关系并引用主表的列

五大约束的语法示例
 

    1. —-添加主键约束(将stuNo作为主键)
       alter table stuInfo
       add constraint PK_stuNo primary key (stuNo)
    2. —-添加唯一约束(身份证号唯一,因为每个人的都不一样)
       alter table stuInfo
       add constraint UQ_stuID unique(stuID)
    3. —-添加默认约束(如果地址不填 默认为“地址不详”)
       alter table stuInfo
       add constraint DF_stuAddress default (‘地址不详’) for stuAddress
    4. —-添加检查约束 (对年龄加以限定 15-40岁之间)
       alter table stuInfo
       add constraint CK_stuAge check (stuAge between 15 and 40)
       alter table stuInfo
       add constraint CK_stuSex check (stuSex=’男’ or stuSex=’女′)
    5. -- Create/Recreate primary, unique and foreign key constraints
      alter table ALL_SEQUENCE
      add primary key (NAME)
      ;
      -- Create/Recreate check constraints
      alter table ALL_SEQUENCE
      add constraint ALL_SEQUENCE_CHK1
      check (to_number(CURRENT_VALUE)>=to_number(MIN_VALUE) and to_number(CURRENT_VALUE)<=to_number(MAX_VALUE));

    6. —-添加外键约束 (主表stuInfo和从表stuMarks建立关系,关联字段stuNo)

数据库五大约束使用方法

原文:https://www.cnblogs.com/jishumonkey/p/11833460.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!