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)  
  • 相关阅读:
    ASP程序调用验证码
    fcex pf.conf
    高速INTERNET代理服务器解决方案
    《IIS 6的几个经典问答》
    一个符合WEB标准的横向下拉菜单
    FREEBSD+PF 在6.2上的架设
    权限
    FreeBSD+IPFILTER实现整网(N个Vlan)透明代理上网
    pf 带宽控制 例子
    FreeBSD下配置DHCP服务小结
  • 原文地址:https://www.cnblogs.com/xiaowie/p/8674980.html
Copyright © 2011-2022 走看看