目录
1、使用 SQL 创建数据表
--语法 :
create table 表名(
字段名 数据类型(大小),
字段名 数据类型(大小),
....
字段名 数据类型(大小));
--eg:
create table teacher(
t_no varchar2(10) primary key,
t_name varchar2(10),
t_money number(6,2),
t_sex char(5),
t_bron date
);
2、用 SQL 创建约束
(1)主键约束:可在建表时创建
--语法:
alter table 表名 add constraint 主键名 primary key(主键字段名);
(2)外键约束:
--语法:
alter table 表名 add constraint 外键名 foreign key(外键字段名) references 参考表名(参考主键字段名);
(3)唯一约束:
--语法:
alter table 表名 add constraint 唯一约束名 unique(约束字段名);
(4)默认约束:可在建表时创建
--语法:
alter table 表名 Modify 字段名 数据类型(长度) default('值');
(5)检查约束:
--语法:
alter table 表名 add constraint 检查约束名 check(约束条件);
(6)添加注释:
--语法:
表注释:
comment on table 表名 is '注释名';
列注释:
comment on column 表名.列名 is '注释名';
3、EG展示:
--创建课程表
drop table score;--为了避免表重复创建,进行删除之前相同的表
create table score(
s_id varchar2(10) primary key,
s_name varchar2(20) not null,
s_sid varchar2(20) ,
s_type varchar2(20) default '文学类',
t_no varchar2(10),
s_date number(10)
);
--主键
--alter table score add constraint PK_name primary key(s_name);
--唯一指引
alter table score add constraint un_sid unique(s_sid);
--外键
alter table score add constraint FK_no foreign key(t_no) references teacher(t_no);
--默认值
alter table score modify s_type varchar2(20) default('教育类');
--自定义约束
alter table score add constraint CK_date check(s_date>0 and s_date<=10);