1.sqlplus进入oracle数据库
sqlplus username/password —进入本地服务
sql
2.修改用户默认表空间
alter user sofa default tablespace ACS;
3.查询所有表空间
select * from v$tablespace;
4.查看某个用户所属的表空间
select username,default_tablespace from dba_users where username=‘SOFA’;
5.表空间用户关系
https://www.cnblogs.com/createyuan/p/5889720.html
http://www.cnblogs.com/cici-new/archive/2012/12/25/2831740.html
6.命令行查询表的字段及类型
SELECT * FROM USER_TAB_COLUMNS WHERE TABLE_NAME=‘T_USER’ 或者DESC tablename
这个表中没有备注,,查备注要用all_col_conmments这个表
7.批量导入sql脚本
新建step.sql脚本,内容如下
@D:\Users\caojx\Desktop\testsql\test1.sql;
@D:\Users\caojx\Desktop\testsql\test2.sql;
sqlplus中执行
SQL> @D:\Users\caojx\Desktop\testsql\step.sql;
8.一般的oracle用户授权
对于普通用户:授予connect, resource权限。
对于DBA管理用户:授予connect,resource, dba权限。
9.Oracle11g常用数据字典查询
https://www.cnblogs.com/liuguosong/p/5808642.html
10.改变表空间状态
改为只读/读写
alter tablespace sofa read only/read write;
11.更改表的状态
alter table sofa read only;
12.查看当前数据库的字符集
select * from nLS_database_parameters where parameter=‘NLS_CHARACTERSET’;
13.以dba身份进入oracle:
cmd》》sqlplus》》用户名》》》密码:键入密码 as sysdba 回车
14.查询某个用户拥有的权限(只有dba能查)
select * from dba_tab_privs where grantee=‘sofa’;
15.权限可以传递(这样sofa就可以将建表的权限grant给别人)
grant create table to sofa with admin option;
16.只有dba能查看dba_开头的表,查角色或者用户的权限可以这样:
select * from dba_sys_privs/user_sys_privs/role_sys_privs where granee/username/role=‘sofa’;
https://zhidao.baidu.com/question/1753781551571612188.html
17.查询当前用户所拥有的角色
select * from user_role_prives
18.查询当前会话所拥有的角色(一个会话以一个命令窗口为准)
select * from session_roles;
19.通过rowid查询某一行所在的数据文件
select file_name, file_id from dba_data_files where file_id in (select distinct dbms_rowid.rowid_relative_fno(rowid) from sofa.demovo)
20.oracle中修改表中列名和列类型
alter table uu modify id number(20);
alter table uu rename column name to nameq;(重命名列名)
更改表中记录用update;
https://blog.csdn.net/zheng0518/article/details/44947265
21.group by 组内分组
select forigin_type,fgender,count(fid) from t_user group by forigin_type,fgender
22.树状存储数据查询某一个节点底下所有的数据
select dm1.name,dm2.* from (select name from demovo where employee_id=10) dm1, demovo dm2 start with dm2.manager_id=10 connect by prior dm2.employee_id=dm2.manager_id
23.exists使用举例
查找管理层人员
in: select em1.name from demovo em1 where em1.employee_id in
(select distinct em2.manager_id from demovo em2)
exists:select em1.name from demovo em1 where exists (select * from demovo em2 where em1.employee_id=em2.manager_id)
24.复制表结构和表数据
create table tb as select * from sofa where 1=2/1=1
25.update可以set选择的值
update tb set name = (select name from sofa whereid =1)要保证选择出的值是单一的
26. ltrim和rtrim的作用
select ltrim(‘sfdsfs’,‘sf’) from dual;
结果:dsfs
从左边开始,将左侧字符串中每一个字符都在右侧字符数组中找一下,如果有,则去掉,如果没有,则命令结束,rtrim则从右侧开始找并去除,功能一样
27.查询表空间的大小和查询表空间可用大小
可用大小:
select tablespace_name,sum(bytes)/1024/1024 MB from user_free_space
group by tablespace_name;
初始化大小
select tablespace_name,sum(bytes)/1024/1024 MB from dba_data_files
group by tablespace_name;
28. 查看当前用户的详细信息
select * from user_users;
https://www.cnblogs.com/lichuangblog/p/6892931.html
29. 查看当前数据库的一些详细参数(比如查询字符编码)
SELECT * FROM NLS_DATABASE_PARAMETERS ;
30. 一个用户查询另一个用户的表
权限:grant select any table to acs
单表:grant select on sofa.demo to acs
无法通过一条命令只将sofa中的所有表查询权限给acs,要么所有方案中的表,要么单表,要么只能生成语句,一条条执行
https://blog.csdn.net/u013895412/article/details/54093709
30.imp 导入表,ignore=y 表示忽略创建错误,继续后面的操作,full=y是全表导入
31.order by的伪列查询不太一样
32.oracle带排序的分页查询,利用结果集的rownum伪列,最内侧排序(order by 的rownum是先查出来,每一行给了rownum之后 才orderby的),第二层查第一行到分页截止行,查出的结果中有一列是第二层的伪列(对于最外层来说这个伪列就是普通的列),然后对这个伪列进行筛选
select rownum rn3 ,t3.fid,t3.fname from (
select rownum rn2,t2.* from(
select rownum rno,t1.* from t_pa_product t1 order by fname) t2
where rownum<=20) t3 where rn2>10
33.rownum的讲解
https://www.cnblogs.com/szlbm/p/5806070.html
34.sql中改变日期时间格式化为字符串去和string类型比较
to_char(fcreate_time,‘YYYY-MM-DD’)=:date
35.java.math.BigDecimal cannot be cast to java.lang.String ,聚合函数的数字java中是bigDecimal格式的,用bigDecimal接收,然后intValue()转化
http://www.cnblogs.com/digdeep/p/4600907.html
36.正则表达式的应用oracle
select count(fsubject) from(select t2.fsubject,listagg(t2.fstatus,",)
within group (order by fsubject)status
inner join t wb_execution t2 on t1.fid e t2.fsubject
from t pa product tl
where to_char(t2.fdate,'YYYY-MM-DD')='2019-04-16'and t1.foperation_unit=1
group by t2.fsubject)t3
where
regexp_like(status,'[1-6]') --这里查的是1-6这6个数字字符一个都匹配不上的结果
https://lucizhang.iteye.com/blog/2305159
37.同时查两个不同条件的统计值,减少io次数
select (select count() from t1) as success,(select count()from t2) as fail from dual
38.**将字符串分类汇总成一个字段 oracle c12中用listagg(t2.fstatus,",)**查的结果如下,查出来之后再做处理,(本次是查产品任务链执行状态中有一条不异常就算失败的用到了汇总字符串)见上面sql
39.select * from table for update 行级锁
(1)不加where条件 会锁住所有行,阻塞其他session,除非本session执行commit
(2)加条件,则只会锁住某一行,不会影响其他行,wait是指等待的时间
select * from t_todo_todo where fid=‘19042519134296000308’ for update wait 2
40.关于视图v&session 的讲解
http://blog.itpub.net/12679300/viewspace-1108154/
41.导库的步骤:
第一步:创建表空间
create tablespace farmdoab datafile 'D:\dzzwpt.dbf' size 100M autoextend on next 50m;
第二步:创建目录
create or replace directory acs_dir as 'D:\DMP';
PS:把要导入的DMP文件放入目录下。
第三步:创建用户,并指定默认的表空间
create user cxdb identified by root default tablespace farmdoab;
--》》(删除用户:drop user iteye cascade;)
第四步:授权
4.1:授权dba权限:grant connect, dba to cxdb;
4.2:授权用户cxdb读写目录文件: grant read, write on directory dp_dir to cxdb;
第五步:导入DMP文件
impdp acs/acs@ORCL directory=acs_dir dumpfile=PAACS.dmp full=y;
PS:lodfile可以不加,不加系统自动创建。
expdp acs/acs@orcl dumpfile=paacs.dmp logfile=full.log directory=data_pump_dir tablespaces=ACS,ACS_IDX
41.oracle分组拼接字符串的用法和场景
----11g的分组拼接字符串
select t2.fsubject,wmsys.wm_concat(t2.fstatus)status from
t_wb_execution t2 group by t2.fsubject
---12c用 listagg(t2.fstatus,',') within group (order by fsubject)status
select t2.fsubject,listagg(t2.fstatus,',') within group (order by fsubject)status from
t_wb_execution t2 group by t2.fsubject
正常查询
分组合并字符串
42.oracle列加别名 应该用"别名" 双引号
43.oracle中的执行计划:https://blog.csdn.net/Dongguabai/article/details/84309062
expain plan for select…
select * from table(dbms_xplan.display)
44.查看一个表的索引情况比如聚簇因子,表中物理存储的块等信息
----查块和行数
select blocks,num_rows from user_tables a where a.table_name='TEMPTABLE'
select * from temptable
----查聚簇因子
select a.index_name,a.table_name,a.num_rows,
a.clustering_factor
from user_indexes a where a.table_name='TEMPTABLE'
---反转索引
alter index ind rebuild reverse
45.反转索引,使得新建的索引顺序混乱分布,这样索引的性能会变得很差,因为已经不是按照rowid顺序排列的了
46.dblink建立语句:create public database link lnk_test1 connect to sofa identified by acs using ‘127.0.0.1:1521/ORCL’;
删除:DROP PUBLIC DATABASE LINK [name];
查询:select * from dba_db_links;
select owner,object_name from dba_objects where object_type=‘DATABASE LINK’;
select * from ALL_DB_LINKS;
https://blog.csdn.net/xjz2000/article/details/80521591
47.oracle中几个特殊sql语句:
merge当条件匹配时执行某个操作,当条件不匹配时执行另一个操作
----merge当条件匹配时执行某个操作,当条件不匹配时执行某个操作
merge into todobak b using t_todo_todo t on
(b.fid=t.fid) when matched then update set b.fsubject=t.fsubject
when not matched then insert (b.fid,b.fsubject,b.ftaskid,b.femergency,b.fexecutorflag)
values(t.fid,t.fsubject,t.ftaskid,t.femergency,t.fexecutorflag);
select * from t_todo_todo
insert all 一次读取的结果一次性插入多张表中
insert all when ftaskid<190623000092 then into todobak
else into todobak1
select * from t_todo_todo
connect by/start with查找某一个父节点下所有的子节点行,而自连接的只能向下查找一个子节点
select fid,fname,flevel,level from t_pa_pro_type start with fid=15082413432869559601
connect by prior fid=fparent_id
48.批量插入数据 insert into table1 select * from table2
49.造数,每一行插入一个递增的id
update dba_1 set fid=i where fid is null and rownum<2;
declare
i number(20) default to_number(to_char(sysdate,'yyyymmddhhmmss'));
j number(20) default 0;
begin
---开始循环
while (j < 610808) loop
update dba_1 set fid=i where fid is null and rownum<2;
i := i + 1;
----结束循环
end loop;
commit;
end;
50.oracle清空当前会话内存中的缓存数据 alter session set events ‘immediate trace name flush_cache level 1’
51.oracle ORA-01653 表空间无法扩展的解决方法:
https://www.cnblogs.com/arxive/p/6885041.html
----查询表空间使用情况---
SELECT UPPER(F.TABLESPACE_NAME) "表空间名",
D.TOT_GROOTTE_MB "表空间大小(M)",
D.TOT_GROOTTE_MB - F.TOTAL_BYTES "已使用空间(M)",
TO_CHAR(ROUND((D.TOT_GROOTTE_MB - F.TOTAL_BYTES) / D.TOT_GROOTTE_MB * 100,2),'990.99') "使用比",
F.TOTAL_BYTES "空闲空间(M)",
F.MAX_BYTES "最大块(M)"
FROM (SELECT TABLESPACE_NAME,
ROUND(SUM(BYTES) / (1024 * 1024), 2) TOTAL_BYTES,
ROUND(MAX(BYTES) / (1024 * 1024), 2) MAX_BYTES
FROM SYS.DBA_FREE_SPACE
GROUP BY TABLESPACE_NAME) F,
(SELECT DD.TABLESPACE_NAME,
ROUND(SUM(DD.BYTES) / (1024 * 1024), 2) TOT_GROOTTE_MB
FROM SYS.DBA_DATA_FILES DD
GROUP BY DD.TABLESPACE_NAME) D
WHERE D.TABLESPACE_NAME = F.TABLESPACE_NAME
ORDER BY 4 DESC;
------增加数据文件扩展表空间并允许数据文件自动扩展
ALTER TABLESPACE SOFA ADD DATAFILE --sofa是表空间名称
'E:\ORACLE\SOFA2.DBF' SIZE 100M
AUTOEXTEND ON NEXT 5M MAXSIZE 100M;
52.普通表改为分区表的几种方式
https://www.2cto.com/database/201111/112034.html
可以新建一张分区表,将原表数据insert 然后再改名,建立原本有的索引
53.分区表的建立、删除和查看
----创建分区
create table dba_2_new
partition by range (object_id)
(partition p1 values less than (20000),
partition p2 values less than (40000),
partition p3 values less than (60000),
partition p4 values less than (80000),
partition p5 values less than (maxvalue))
as select * from dba_2 where 1=2
insert into dba_2_old select * from dba_2
----查看分区
select * from user_tab_partitions where table_name='DBA_2'
--删除分区
ALTER TABLE DBA_2 TRUNCATE PARTITION (p1);
ALTER TABLE DBA_2 TRUNCATE PARTITION (p2);
.....
54.to_date的使用方法,to_char也类似
https://blog.csdn.net/myitec/article/details/51113019
55.查询锁表,以及锁表的字段解释
https://www.cnblogs.com/dgq-blog/p/9243196.html
`select t2.username,
t2.sid,
t2.serial#,
t3.object_name,
t2.OSUSER,
t2.MACHINE,
t2.PROGRAM,
t2.LOGON_TIME,
t2.COMMAND,
t2.LOCKWAIT,
t2.SADDR,
t2.PADDR,
t2.TADDR,
t2.SQL_ADDRESS,
t1.LOCKED_MODE
from v$locked_object t1, v$session t2, dba_objects t3
where t1.session_id = t2.sid
and t1.object_id = t3.object_id
order by t2.logon_time;`
另外查v$session的event事件,如果有sql因为锁一直堵着,可以看看这个事件里会显示
ORACLE里锁有以下几种模式:
0:none
1:null 空
2:Row-S 行共享(RS):共享表锁,sub share
3:Row-X 行独占(RX):用于行的修改,sub exclusive
4:Share 共享锁(S):阻止其他DML操作,share
5:S/Row-X 共享行独占(SRX):阻止其他事务操作,share/sub exclusive
6:exclusive 独占(X):独立访问使用,exclusive
56.oracle中分组并得到汇总
select p_type,p_name,sum(p_count),sum(p_money) from test group by rollup(p_type,p_name)
57.oracle中查询打开未关闭的游标数
--按用户和机器以及游标未关闭的sql查看
select o.sid,O.sql_text, osuser, machine, count(*) num_curs
from v$open_cursor o, v$session s
where o.sid=s.sid and o.cursor_type='OPEN'
group by o.sid, osuser, machine,o.sql_text
order by num_curs desc;
查总数
select count(*) from v$open_cursor where curesor_type='OPEN'
ps:oracle游标未关闭的原因分析:
此问题的最常见成因是未正常关闭 JDBC 对象。使用诊断查询中第三个查询的结果在应用程序代码中反向跟踪,确保将所有 JDBC 对象都正常关闭。BEA 建议在 finally 块中显式关闭 Connection、Statement 和 ResultSet 等 JDBC 对象,以确保无论是在正常还是异常情况下都将所有 JDBC 对象关闭,且打开和关闭的次数应该是一一对应
正确示例:
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = getConnection(); //Method getConnection will return a JDBC Connection
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from empdemo");
// do work
} catch (Exception e) {
// handle any exceptions
} finally { //finally里面手工关闭jdbc的对象
try {
if(rs != null)
rs.close();
} catch (SQLException rse) {}
try {
if(stmt != null)
stmt.close();
} catch (SQLException sse) {}
try {
if(conn != null)
conn.close();
} catch (SQLException cse) {}
}
错误示例:
Connection conn = null;
try{
conn = getConnection(); //一个connection对象
//for循环中多个statement和resultSet对象
for(int i = 0; i < NUM_STMT; i++) {
Statement stmt = null;
ResultSet rs = null;
stmt = conn.createStatement();
rs = stmt.executeQuery(/*some query*/);
//do work
}
} catch(SQLException e) {
// handle any exceptions
} finally { //finally中只关闭了一次对象,可能引起在for循环结束之前就报游标超数
try{
if(rs != null)
rs.close();
} catch (SQLException rse) {}
try {
if(stmt != null)
stmt.close();
} catch (SQLException sse) {}
try {
if(conn != null)
conn.close();
} catch (SQLException cse) {}
}
57.oracle中格式化日期格式注意事项:
(1)各种格式化 参考 https://www.cnblogs.com/cainiao-Shun666/p/6877667.html
(2)注意oracle分钟和时间的表示:
MI 返回指定时间的分钟(范围0-59)(注意java表示分钟是mm,月份是MM,而Oracle表示分钟是mi,月份是MM)
select to_char(sysdate,'HH24') from dual; --24小时制,12类似
select to_char(sysdate,'MI') from dual; ---mi/MI表示分钟 而非MM
select to_date(to_char(sysdate,'yyyy/MM/dd HH24:mi'),'yyyy/MM/dd HH24:mi') from dual
58.查找某个主键与之对应的外键关联关系
select a.constraint_type,a.table_name,a.status, b.table_name,b.column_name,b.constraint_name from user_constraints a
inner join user_cons_columns b
on a.constraint_name = b.constraint_name
where a.r_constraint_name='约束名'
59.查找数据库执行慢或者说堵塞住的sql
select username ,q.MACHINE, sid,sql_text,sql_fulltext,q.sql_id,event,q.blocking_session
from v$session q,v$sql s where status='ACTIVE' and s.sql_id=q.sql_id
and username is not null;
上个sql中的event会说明是什么原因导致的一直在执行,如果sql已经执行完了,但是没有提交,则不算ACTIVE,active说的是正在执行或者等待执行的sql
69.杀死oracle中的session:
--释放session Sql:
alter system kill session 'sid, serial#'
eg:
alter system kill session '30, 2412';
60.删除表中字段重复的记录
delete from t_todo_Todo t where t.fproductid in (select fproductid from
t_todo_todo group by fproductid having count(*)>1 ) --先找出重复的列值
and t.rowid not in /*not in 把不等于最小rowid的记录都晒选出来,删掉之后剩下的就是每组最小的rowid也就去重 了
*/(select min(rowid)/*或者max(rowid)也可以,只是为了拿到任意一个值而已*/ from t_todo_todo group by fproductid
having count(*)>1)
61.oracle中查询当前用户下所有的表:
select *from user_tables