您的位置:首页 > 数据库 > Oracle

oracle 数据库表基础操作,创建表,修改列,约束

2018-01-12 18:08 477 查看
1.创建表并添加相应的约束。要求:
(1)创建名为student(学生信息)的表,表中各列要求如下:

字段名称

字段类型

大小

说明

sno

CHAR

10

主键

sname

VARCHAR

8

sex

CHAR

2

默认值为男,只能输入男或者女

birthday

DATE

sdept

CHAR

20

create table student
(
sno char(10) primary key,
sname varchar2(8),
sex char(2) default '男' , constraint ch_sex check(sex in('男','女')), --添加约束,约束名ch_sex。默认值为男,只能输入男或者女
birthday date,
sdept char(20)
);

select * from student;

alter table student modify sname varchar(9); --修改一列
alter table student add test varchar(2); --添加一列
alter table student drop column test; -- 删除一列
--这里要注意几个地方,首先,增加和修改列是不需要加关键字COLUMN,否则会报错ora-00905。其次,对删除单列的话,一定要加COLUMN,然后记住,删除是不需要加列类型的。

alter table student modify (sno char(12),sname varchar(9)); --修改多列
alter table student add (test1 varchar(2),test2 varchar(2)); --添加多列
alter table student drop (test1,test2); -- 删除多列
--很奇怪的现象,再单列中要加关键字COLUMN,然而再删除多列的时候,不能加COLUMN关键字。

desc student;
drop table student;

insert into student values('01','我是谁','女',to_date('2018/01/11','yyyy/mm/dd'),'021-');
delete student where sno='01';

alter table student rename column sname to new_sname; --修改列名: old to new;

(2)创建名为course(课程信息)的表,表中各列要求如下:

字段名称

字段类型

大小

说明

cno

CHAR

10

主键

cname

CHAR

30

唯一性

ccredit

NUMBER

3

create table course
(
cno char(10) primary key, --主键无命名,可以查询: SELECT * FROM USER_CONS_COLUMNS where table_name='STUDENT';
cname char(30) unique,
ccredit number(3)
);
alter table course drop primary key;
alter table course add primary key(cno);

create table course
(
cno char(10), constraint p_cour primary key(cno), --主键有命名,系统会自动将列置为非空
cname char(30) unique,
ccredit number(3)
);
alter table course add constraint p_cour primary key(cno);
alter table course drop primary key;

select * from course;
desc course;
drop table course;

(3)创建名为score(学生成绩)的表,表中各列要求如下:

字段名称

字段类型

大小

取值范围

说明

sno

CHAR

10

数据来自学生信息表

主键

cno

CHAR

10

数据来自学生课程表

主键

grade

NUMBER

3

0~100

create table score
(
sno char(10),
cno char(10) ,
primary key(sno,cno), --联合主键
grade number(3) constraint ww check(grade>=0 and grade <=100) --检查约束(check)
);

alter table score add constraint fk_scor1 foreign key(sno) references student(sno);
alter table score add constraint fk_scor2 foreign key(cno) references course(cno);

alter table score drop constraint fk_scor1,fk_scor2 ;
select * from score;
desc score;
drop table score;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐