Oracle----表操作
创建表
##首先连接到对应的用户下,如果已经是对应的用户则忽略 conn gary/gary as sysdba; ##创建表 create table t1(id int not null,name varchar(8) not null,tel int not null);
查询插入表
//不会为该表创建字段约束 create table table_name as select * from table_name;
创建临时表
这种临时表不占用表空间,而且不同的SESSION之间互相看不到对方的数据,在会话结束后表中的数据自动清空
1、方法一,则在提交后(commit),即清空表里面数据
CREATE GLOBAL TEMPORARY TABLE TABLENAME ( COL1 VARCHAR2(10), COL2 NUMBER ) ON COMMIT PRESERVE ROWS ;
2、方法二,一直到会话结束,清空表里面数据
CREATE GLOBAL TEMPORARY TABLE TABLENAME ( COL1 VARCHAR2(10), COL2 NUMBER ) ON COMMIT DELETE ROWS ;
修改表
##修改表名 rename t1 to tb1; ##增加字段 alter table tb1 add sex char(4); ##修改字段名 alter table tb1 rename column tel to tell; ##删除字段 alter table tb1 drop column sex; ##修改字段类型 alter table tb1 modify sex int; ##给表/表字段添加注释 COMMENT ON TABLE REPO_DEAL IS '交易表'; COMMENT ON COLUMN REPO_DEAL.rtranname IS '业务柜员姓名';
删除表
##删除表中的所有数据,速度比delete快很多,截断表 truncate table 表名 delete from table 条件 #删除表 drop table 表名
创建视图
如果经常查几个关联表,就把查询写个视图,省得每次都要写很长的语句。
高级使用
constraint
约束条件
- not null 使得数据库的字段值不能为空
- unique 使得所有行中不存在相同值,当时允许同时为空
- primary key 主键约束,不能为空,且字段值不能相同
- foreign key 必须在相应的表中存在该字段且存在对应的值
- check 满足check中的条件
- ref
创建表添加约束)
//检查索引 create table table_name ( gender varchar2(4) constraint gender_error check(gender in ('男','女')) ); //主键索引和非空 create table SYS_USERS ( USERID VARCHAR2(40) not null constraint PK_SYS_USERS primary key )
修改表添加约束
--方法1: alter table table_name modify gender constraint gender_error check(gender in('男','女')); --方法2: alter table table_name add constraint gender_error check(gender in('男','女')); --添加唯一约束 alter table emp add constraint emp_code_uq unique(code); --非空约束 alter table emp modify ename not null; --外键约束(FOREIGN KEY) #删除的时候,级联删除掉子表中的所有匹配行,在创建外键时,通过 on delete cascade 子句指定该外键列可级联删除: alter table emp add constraint emp_deptno_fk foreign key(deptno) references dept (deptno) on delete cascade; #删除父表中的对应行,会将对应子表中的所有匹配行的外键约束列置为NULL,通过 on delete set null 子句实施: alter table emp add constraint emp_deptno_fk foreign key(deptno) references dept(deptno) on delete set null;
删除/禁用/启动约束
--删除约束 alter table table_name drop constraint gender_error; --禁用约束1 alter table table_name add constraint error uniqe(column_name) disable; --禁用约束2 alter table table_name disable constraint error ; --启用约束 alter table table_name enable constraint error ; --这时,如果在禁用的过程中插入了不满足要求的数据,可以使用enable novalidate可以选择只对新数据应用这个约束 alter table table_name enable novalidate constraint error ;