• 关系数据模型常见约束的语法总结


    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))
  • 相关阅读:
    CDOJ 1270 Playfair(模拟)
    HDU 2209 翻纸牌游戏(DFS)
    HDU 1241 Oil Deposits(DFS)
    pta 01-复杂度2 Maximum Subsequence Sum (25分)
    poj 1469 COURSES 二分匹配 dfs
    01-复杂度1 最大子列和问题 (20分)分治
    poj 1325 Machine Schedule 二分图匹配+DFS实现
    zoj 1654 Place the Robots 二分图匹配DFS实现
    图论笔记-第七章
    hdu 5423 Rikka with Tree DFS
  • 原文地址:https://www.cnblogs.com/zuixime0515/p/10499578.html
Copyright © 2020-2023  润新知