【数据库】基本表的定义、删除与修改

请注意,本文编写于 593 天前,最后修改于 592 天前,其中某些信息可能已经过时。

一、定义数据表

1、建立一个“学生”表student。

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(···);
create table "S-T".course(···);
create table "S-T".sc(···);
四、修改基本表

【例】向student表增加“入学时间”列,其数据类型为日期型

alter table student add S_entrance date;

【例】修改student表的Sage字段默认值为20

alter table student alter column Sage set default 20; /*修改student表的Sage字段的默认值为20*/

【例】将student表的Sage由字符型改为整型。

alter table student modify column Sage int;

【例】增加课程名必须取唯一的约束条件。

alter table course add unique(Cname);
五、删除基本表

若选择restrict ,则该表的删除是有限制的,欲删除的基本表不能被删除。

若选择cascade,则删除没有限制,在删除表的同时,相关依赖对象,例如视图,都将被一起删除。

drop table student restrict|cascade;

添加新评论

已有 2 条评论