我的Oracle数据库学习笔记
Day 2 修改表结构
创建学生表
create table student
(
studentId int ,
studentName nvarchar2(10),
sex nchar(1),
age int,
phone char(11),
address nvarchar2(50)
);
查看表中数据
select * from student;
删除表
drop table 表名;
例:drop table student;
设置字段是否为空,保证数据必埴或可选
当创建表时,如果没有设置字段是否为空,则默认为可空的
指定列为必填项时,在创建表时设置为非空项 :not null
create table student
(
studentId int not null ,
studentName nvarchar2(10) not null,
sex nchar(1) not null,
age int not null,
phone char(11),
address nvarchar2(50)
);
修改表结构
1.修改表中的列
给student表中sex列添加一个默认值(男)
- 创建表时指定默认值 (必须写在not null前面)
sex nchar(1) default('男') not null,
- 修改现有表中列的属性
alter table 表名 modify(列名 数据类型(长度) 是否可空);
例:
alter table student modify(sex default('男'));
添加新列
给Student表中添加一个新列,email
- 把表删除掉,重新创建
- 给现有表添加新列
alter table 表名 add(列名 数据类型(长度) 是否可空);
例:
alter table student add(email varchar2(100) default('oracle@126.com') not null);
--给Student表中添加新列学生描述 (可空)
alter table student add(studentInfo varchar2(100));
注意事项:
1)如果现有表中已有数据,则添加新列时不能指定为非空列
2)如果现有表中已有数据,新列为非空列则需要指定一个默认值
删除表中的列
把student表中 studentInfo列删除掉
1 把表中列删除
alter table 表名 drop(列名);
alter table 表名 drop column 列名;
例:
alter table student drop (studentInfo);
alter table student drop column studentInfo;
注意:列中有无数据都可以删除。
给表或列添加注释
comment on table 表名 is 'text' -- 给表添加注释
comment on column 表名.列名 is 'text' --给表中的列添加注释
例:
给student表添加注释 :学生信息表
comment on table student is '学生信息表';
student表中的studentId(学生编号) ,studentName(学生注释)
comment on column student.studentId is '学生编号';
comment on column student.studentName is'学生姓名';
给表或列改名
给表改名:
rename 原表名 to 新表名;`
给列改名:
alter table 表名 rename column 原列名 to 新列名;
例:
修改Student表名为:studentInfo
rename student to studentInfo;
修改studentInfo表中的studentName 改为stuName;
alter table studentInfo rename column studentName to stuName;