数据库五大约束使用方法


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

  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. —-添加外键约束 (主表stuInfo和从表stuMarks建立关系,关联字段stuNo)

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM