我的Oracle数据库学习笔记
Day 4 域完整性约束
域完整性约束:限制字段中的值的合理性,范围 约束方式: 非空约束 ,默认值约束,数据类型,检查约束(check约束)
非空约束,默认值约束
1)在创建表时, not null ,default
注意:default要在not null前面
2)给现有表中的列添加非空约束,默认值约束 —>修改列的语法
alter table 表名 modify(列名 默认值 |非空)
check约束
- 性别仅男或女
- 年龄必须在18~50之间
- 邮箱中必须包含’@’
解决方式:check约束
1) 在创建表中时添加 :
字段名 数据类型(长度) check(条件)
2) 给现有表中的字段添加检查约束
alter table 表名
add constraint 约束名 check(约束条件);
约束名:ck_列名 或 列名_ck
例:
- 给学生表中性别列添加检查约束 ,性别仅为男或女
alter table studentinfo
add constraint ck_sex check(sex='男' or sex='女'); --check(sex in('男','女'));
- 给学生表中年龄添加检查约束 ,年龄在18~50
alter table studentInfo
add constraint ck_age check(age >=18 and age <=50); -- check(age between 18 and 50);
- 给学生表中邮箱添加约束 ,值必须包含@
alter table studentinfo
add constraint ck_email check(email like '%@%'); -- %:任意长度的字符