代码改变世界

[学习笔记] Oracle字段类型、建表语句、添加约束

2020-03-08 09:34  小伍2013  阅读(1522)  评论(0编辑  收藏  举报

SQL语句介绍

  • 数据定义语言(DDL),包括 CREATE、 ALTER、 DROP等。
  • 数据操纵语言(DML),包括 INSERT、 UPDATE、 DELETE、 SELECT … FOR UPDATE等。
  • 数据查询语言(DQL),包括基本查询语句、 Order By 子句、 Group By 子句等。
  • 事务控制语言(TCL),包括 COMMIT、 SAVEPOINT、ROLLBACK。
  • 数据控制语言(DCL), GRANT、 REVOKE。

字段类型

VARCHAR2(length)

字符串类型:存储可变的长度的字符串,length是字符串的最大长度,默认是1,最大不超过4000。

CHAR(length)

字符串类型:存储固定长度的字符串,length字符串的固定长度,默认是1,最大不超过2000。

NUMBER(a,b)

数值类型:存储数值类型,可以存整数和浮点型。a代表数值的最大位数,包含小数位和小数点;b代表小数的位数。例子:

number(6,2),输入123.12345,实际存入:123.12 。

number(4,2),输入12312.345,提示不能存入,超过存储的指定的精度。

DATA

时间类型:存储的是日期和时间,包括年、月、日、时、分、秒。

内置函数sysdate获取的就是DATA类型。

TIMESTAMP

时间类型:存储的不仅是日期和时间,还包含了时区。

内置函数systimestamp获取的就是timestamp类型。

CLOB

大字段类型:存储大文本,大于4000长度的字符串。

BLOB

二进制类型:存储的是二进制对象,比如图片、视频、声音等转换过来的二进制对象。

创建表

-- stuinfo学生信息表
create table STUDENT.stuinfo
(
  stuid      varchar2(11) not null,--学号
  stuname    varchar2(50) not null,--学生姓名
  sex        char(1) not null,     --性别
  age        number(2) not null,   --年龄
  classno    varchar2(7) not null, --班号
  stuaddress varchar2(100) default '未录入',  --地址
  grade      char(4) not null,     --年级
  enroldate  date,                 --入学时间
  idnumber   varchar2(18) default '身份证未采集' not null   --身份证
)
-- stuinfo存储的表空间是users
-- storage表示存储参数
-- initial表示区段(extent)一次扩展64k
-- minextents最小区段数为1
-- maxextents最大的区段数不限制
tablespace USERS
  storage
  (
    initial 64K
    minextents 1
    maxextents unlimited
  );
-- Add comments to the table 
comment on table STUDENT.stuinfo
  is '学生信息表';
-- Add comments to the columns 
comment on column STUDENT.stuinfo.stuid
  is '学号';
comment on column STUDENT.stuinfo.stuname
  is '学生姓名';
comment on column STUDENT.stuinfo.sex
  is '学生性别';
comment on column STUDENT.stuinfo.age
  is '学生年龄';
comment on column STUDENT.stuinfo.classno
  is '学生班级号';
comment on column STUDENT.stuinfo.stuaddress
  is '学生住址';
comment on column STUDENT.stuinfo.grade
  is '年级';
comment on column STUDENT.stuinfo.enroldate
  is '入学时间';
comment on column STUDENT.stuinfo.idnumber
  is '身份证号';

添加约束

-- 创建/重建主键索引、唯一索引、外键索引
-- 把 stuid 设为主键,主键字段的数据必须是唯一性的(学号是唯一的)
alter table STUDENT.STUINFO
  add constraint pk_stuinfo_stuid primary key (STUID);
   
-- 创建/重建检查约束
-- 年龄age添加约束,学生的年龄只能0-50岁之间
alter table STUDENT.STUINFO
  add constraint ch_stuinfo_age check (age>0 and age<=50);
   
alter table STUDENT.STUINFO
  add constraint ch_stuinfo_sex
  check (sex='1' or sex='2');
   
alter table STUDENT.STUINFO
  add constraint ch_stuinfo_GRADE
  check (grade>='1900' and grade<='2999');