zoukankan      html  css  js  c++  java
  • 关系数据模型常见约束的语法总结

    Default的设定

    表定义时设定default

    create table pub(
        pub_id char(4) not null,
        pub_name varchar(40) null,
        city   varchar(20)   default 'Pasa',
        state  char(2)         default 'CA')
    

    SQL中字符型数据必须用单引号''括起

    多个表使用相同默认值时

    create default 默认名 as '默认值'
    sp_bindefault '默认名' , '表名.列名'
    
    eg:
    create default dft_state as 'CA'
    sp_bindefault 'dft_state' , ‘pub.state’
    

    这种方法和第一种方法是一样的

    解绑和删除默认名的方法
    sp_unbindefault '表名.列名'
    drop default 默认名

    RULE的设定

    rule主要针对表中的某一列,指明该列的取值范围
    设定方式如下:
    ' create rule 规则名 as 规则'
    ' eg: '
    ' create rule state_rule as @state in('CA','CO','WA') '

    规则可用in(),between ... and ...,关系式<,>,<=,>=,=,!=,!>,!<和like等操作符,其中的@是局部变量说明

    规则创建之后则需要绑定在相应的列上,语法如下

    sp_binrule 规则名, '表名.列名'
    
     eg;
     sp_binrule state_rule ,'pub.state'
    

    规则解绑和删除的语法如下:

    sp_unbinrule  '表名.列名'
    drop rule 规则名
    
    eg:
    sp_unbinrule 'pub.state'
    drop rule state_rule
    

    检查约束的设定

    类似于rule,可对比学习

    列级检查约束定义

    create table pub(
        pub_id char(4) not null
        constraint pub_id_constraint
            check(pub_id in ('123','234','563') or pub_id like('2019[0-9][0-9]'),
        pub_name varchar(40) null,
        city   varchar(20)   default 'Pasa',
        state  char(2)         default 'CA')
    

    表级检查约束

    create table discount(
        discounttype varchar(40) not null,
        store_id         char(4)       null,
        lowqty            smallint      null,
        highqty           smallint      null,
        discount         float            not null,
    
        constraint low_high_check
        check(lowqty <= highqty))
    

    总而言之,表级约束就上面两种写法。

    主键约束的设定

    列级主键约束

    create table stu(
        stuid   char(10) primary key,
        stuname varchar(50) null,
        tel            char(11)      null)
    

    表级主键约束

      create table stu(
            stuid   char(10) primary key,
            stuname varchar(50) null,
            tel            char(11)      null,
            constraint primary_key
                primary key nonclustered(stuid))
  • 相关阅读:
    jquery-4 完整表单验证实例
    从程序员的角度分析微信小程序(编程语言:用到什么学什么)
    微信程序开发
    css3-4 css3边框样式
    css3-3 css3背景样式
    boxfilter 实现
    opencv在arm和x86在移植
    PAT 1033. To Fill or Not to Fill (贪婪)
    [git] fatal: This operation must be run in a work tree
    spring与mybatis集成和事务控制
  • 原文地址:https://www.cnblogs.com/zuixime0515/p/10499578.html
Copyright © 2011-2022 走看看