1. Oracle 表的创建及管理
创建表包括三个要素, 表名, 列名, 数据类型. 每个表都有对应不同的列, 每个列都有唯一对应的数据类型. 常用数据类型简介:
数据类型 | 描述 |
CHARACTER(n) | 字符 / 字符串。固定长度 n。 |
INTEGER(p) | 整数值(没有小数点)。精度 p。 |
NUMERIC(p,s) | 精确数值,精度 p,小数点后位数 s。 |
VARCHAR(n) | 字符 / 字符串。可变长度。最大长度 n。 |
INTEGER | 整数值(没有小数点)。精度 10。存储数据的范围是 - 2 的 31 次方到 2 的 31 次方 - 1,占用 4 个字节的储存空间。 |
DATE | 存储年、月、日的值。 |
TIMESTAMP | 存储年、月、日、小时、分、秒的值。 |
相关语句
-- 例: 创建表名为 table1, 列名为 column1,column2,..., 数据类型为特定数据类型的表
- Create table table1(
- Column1 datetype,
- Column2 datetype,
- ......
- );
-- 添加字段: 在已经建好的表 table1 中添加字段 columnX, 字符类型为 number
- Alter table table1
- add columnX number;
-- 修改字段数据类型: 修改 columnX 的数据类型为 date
- Alter table table1
- Modify columnX date;
-- 修改字段名: 修改 columnX 的名称为 columnY
- Alter table table1
- Rename column columnX to columnY;
-- 删除字段: 删除字段 columnY
- Alter table table1
- Drop column columnY
-- 修改表名: 修改表 table1 的名称为 table2
Rename table1 to table2;
-- 删除表: 删除表 table2:
Drop table table2;
2. 表中的数据管理
添加数据: 在表 table2 中添加数据
注: 往表中添加数据时, 字段数量与值得数量需一直并且一一按顺序匹配, 添加的数据类型要符合表字段的数据类型
- Insert into table2(column1,column2,......)
- Values(value1,value2,......);
添加字段默认数据: 为表中某字段添加默认值, 添加默认值后如果在插入一行数据时该字段没有设定插入的值, 则自动填入默认值.
-- 第一种方法: 在创建表时添加 column1 的默认值为 0
- Create table table1 (
- Column1 number default 0;
- Column2 datetype;
- ......
- );
-- 第二种方法: 创建好表后修改 column 的默认值为 0
- Create table table1 (
- Column1 number;
- Column2 datetype;
- ......
- );
- Alter table table1
- Modify column1 default 0;
复制表数据: 将 table2 中的数据复制到 table1 中
第一种方法: 建表时复制, 此时新建的 table1 与 table2 表结构相同
- Create table table1
- As
- Select * from table2
注: 可加入 where 字句限制限定插入数据
注: 如只需要复制表结构而不需要数据, 则加一不成立的条件即可:
- Create table table1
- As
- Select * from table2
- Where 1=2;
第二种方法: 建表后复制, 复制 table2 中的 column11,column12 两列数据至 table1 的 column1,column2 两列中
- Insert into table1(column1,column2)
- Select column11,column12 from table2
注: 可加入 where 字句限制限定插入数据
修改表数据: 修改表 table1 中 column1 的数据为 value2
- Update table1
- Set column1=value2;
注: 可加入 where 字句限制限定修改数据
删除数据:
第一种方法: 有条件删除
- Delete from table1
- Where ......;
第二种方法: 全部删除, 删除 table1 中所有数据 (不可回滚)
Truncate table table1
来源: http://www.linuxidc.com/Linux/2018-05/152566.htm