zoukankan      html  css  js  c++  java
  • 约束的类型

    约束的类型:

    主键约束: 要求主键列不能为空,要求主键列唯一

    非空约束: 要求该列不能存在空值

    唯一约束: 要求该列的值必须唯一的,允许为空,但只能出一个空值

    检查约束: 限制某列取值的范围是否合适

    默认约束: 设计某列的默认值

    外键约束: 用于在两表之间建立关系,需要指定引用主表是哪一列

    主键约束与唯一约束的区别

    1.主键约束所在的列不允许有空值,唯一约束所列允许为空值

    2.每个表中可以有一个主键,多个唯一约束

    语法

    alter table 表名

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

    约束名的取名规则推荐采用: 约束类型_约束列

    主键[primary key]约束 :如 PK_userid

    唯一[unique key] 约束 :如 UQ_userid

    默认[default key] 约束 :如 DF_userid

    检查[check key]  约束 :如 CK_userid

    外键[foreign key] 约束 :如 FK_userid

    --添加主键约束   
    Alter Table stuInfo   
    Add Constraint  PK_stuNO primary Key(stuNo)   
    ---添加唯一约束   
    Alter Table stuInfo   
    Add Constraint UQ_stuID unique(stuID)   
    ---添加默认约束   
    Alter Table stuInfo   
    Add Constraint DF_stuAddress default('地址不详') for stuAddress   
    ---添加检查约束   
    Alter Table stuInfo   
    Add Constraint CK_stuAge check(stuAge between 15 and 40)   
    ---添加外键约束   
    Alter Table stuMarks   
    Add Constraint FK_stuNo foreign key(stuNo) references stuInfo(stuNo)  
    在创建表的时候同时添加约束的写法:
    use stuDB   
    go   
    if exists(select * from Sysobjects where name = 'stuInfo')   
    drop table stuInfo   
    go   
    create table stuInfo   
    (   
         stuName varchar(20) not null primary key(stuName)    
    ,stuID int not null unique(stuID)   
    ,stuAddress varchar(20) not null default('地址不详')   
    ,stuAge int not null check(stuAge between 15 and 40)  
  • 相关阅读:
    后缀数组简要总结
    2019CCPC网络赛
    2019 Multi-University Training Contest 6
    洛谷P4145——上帝造题的七分钟2 / 花神游历各国
    扫描线——POJ1151
    2012Noip提高组Day2 T3 疫情控制
    2012Noip提高组Day1 T3 开车旅行
    JZOJ.5335【NOIP2017模拟8.24】早苗
    三套函数实现应用层做文件监控
    LLVM一个简单的Pass
  • 原文地址:https://www.cnblogs.com/xiaowie/p/8674980.html
Copyright © 2011-2022 走看看