数据库建⽴表
⼀、定义数据表
1、建⽴⼀个 “学⽣” 表 stu d ent。
create table student
(Sno char(9) primary key,/*主键(主码),列级完整性约束条件*/
Sname char(20) unique,/*Sname 取唯⼀值*/
Ssex char(2),
Sage smallint,
Sdep char(20)
);
2、建⽴⼀个 “课程” 表 course。
create table course
(Cno char(4) primary key,/*Cno主键*/
Cname char(40) not null,/*Cname不能取空值*/
Cpno char(4),/*先修课*/
Ccredit smallint,
foreign key(Cpno) references course(Cno)/*Cpno是外键,对应course的Cno*/
);
3、建⽴学⽣课程表 sc。
create table sc
(Sno char(9),
Cno char(4),
Grade smallint,
primary key(Sno,Cno),/*主码由两个属性构成*/
foreign key(Sno) references student(Sno),
foreign key(Cno) references course(Cno)
);
⼆、数据类型
数据类型含义
char(n),character(n) 长度为n的定长字符串
varchar(n),charactervarying(n) 最⼤长度为n的变长字符串
clob 字符串⼤对象
blob ⼆进制⼤对象
int,integer 长整数(4字节)
smallint 短整数(2字节)
bigint ⼤整数(8字节)
numeric(p,d) 定点数,有p位数字组成,⼩数点后⾯有d位数字
decimal 同numeric
boolean 布尔值
date ⽇期,包含年⽉⽇,格式为YYYY-MM-DD
time 时间,包含⼀⽇的时分秒,格式为HH:MM:SS
timestamp 时间戳类型
interval 时间间隔类型
三、模式与表
⽅法:在表明中明显的给出模式名。
create table "S-T".student(···);
foreign key references用法
create table "S-T".course(···);
create table "S-T".sc(···);
四、修改基本表
【例】向 stu d ent 表增加 “⼊学时间” 列,其数据类型为⽇期型
alter table student add S_entrance date;
【例】修改 stu d ent 表的 Sage 字段默认值为 20
alter table student alter column Sage set default 20; /*修改student表的Sage字段的默认值为20*/【例】将 stu d ent 表的 Sage 由字符型改为整型。
alter table student modify column Sage int;
【例】增加课程名必须取唯⼀的约束条件。
alter table course add unique(Cname);
五、删除基本表
若选择 re s trict , 则该表的删除是有限制的,欲删除的基本表不能被删除。
若选择 cas c ade,则删除没有限制,在删除表的同时,相关依赖对象,例如视图,都将被⼀起删除。drop table student restrict|cascade;

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。