oracle常用命令
Posted _雪辉_
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了oracle常用命令相关的知识,希望对你有一定的参考价值。
public ip:
类似与单实例的oracle数据库ip,主要用于管理访问。
virtual ip(vip):
oracle在rac架构中专用,这个vip用于实现故障转移,当一个节点发生故障时,其vip会“浮动”到另外一个正常的节点,也即该正常节点对应着两个vip了。
SCAN:
Single Client Access Name,单一客户访问名称,意思是客户端(如jdbc,pl/sql等)访问数据库时的公共域名,由于rac是多节点的,客户端要访问数据库,通过scan机制,只需要提供一个访问名称,oracle rac会自动为客户端分配一个节点,这对客户端来说是透明的。
private ip:私有ip,oracle 内部用于节点间通讯的ip,不对外开放。
public ip:
必须是专用ip,必须在安装oracle rac前配置好,能与网络连通。public ip,vip,scan ip必须在同一个网络网段内。
vip:
必须是专用ip,必须安装oracle rac前配置好,能与网络连通,public ip,vip,scan ip必须在同一个网络网段内。该ip及域名虽然配置,但必须保持不能使用(不能被访问,如ping)。
scan :
建议通过dns配置三个专用ip,在安装前必须配置好,当有请求者时,由dns随机分配。暂不使用。scan ip需要给出唯一的名字,也即三个ip对应一个域名。名字只能是字符和'-'。oracle不推荐通过hosts文件来配置,那样只能得到一个scan ip。
scan也是一个虚拟ip名,类似与虚拟ip名,但不同的是,虚拟ip是一个节点一个ip地址一个域名,scan是针对整个cluster的,一个域名对应着多个节点,多个ip地址。
private ip:
必须是专用ip,必须在安装前配置好,必须在一个专用私有网络中,只能被另外的rac节点解析,不能被其它网络解析。从11.2.0.2开始,oracle可以自动使用至多4块私有网卡,以实现内部节点的负载均衡及冗余。
设置一个事务的隔离级别
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
SET TRANSACTION READ ONLY;
设置增个会话的隔离级别
ALTER SESSION SET ISOLATION_LEVEL SERIALIZABLE;
ALTER SESSION SET ISOLATION_LEVEL READ COMMITTED;
ALTER SYSTEM SET AUDIT_TRAIL=NONE SCOPE=SPFILE SID='*';--关闭审计
alter system set deferred_segment_creation=false SCOPE=BOTH SID='*'; --关闭段创建延迟
#ALTER SYSTEM SET SEC_CASE_SENSITIVE_LOGON=FALSE SCOPE=SPFILE SID='*'; --关闭密码大小写验证,在12c版本中此参数已被弃用,如果手动改为FALSE,除非设置正确的SQLNET.ALLOWED_LOGON_VERSION_SERVER参数,否则所有用户都会无法登陆,因此不要这么改了。
ALTER PROFILE DEFAULT LIMIT FAILED_LOGIN_ATTEMPTS UNLIMITED;--设置登录次数为无限
ALTER SYSTEM SET CONTROL_FILE_RECORD_KEEP_TIME=31 SCOPE=BOTH SID='*';--控制文件内容保存时间
ALTER SYSTEM SET MAX_DUMP_FILE_SIZE='2048M' SCOPE=BOTH SID='*';--DUMP文件size的最大值
ALTER SYSTEM SET PROCESSES=2048 SCOPE=SPFILE SID='*';--最大进程数
ALTER SYSTEM SET "_UNDO_AUTOTUNE"=FALSE SCOPE=BOTH SID='*';--关闭UNDO自动调优的功能
ALTER SYSTEM SET "_USE_ADAPTIVE_LOG_FILE_SYNC"=FALSE SCOPE=BOTH SID='*'; --关闭自适应日志同步功能
alter database add supplemental log data; --打开附加日志,便于进行故障后数据找回
检查集群状态
crsctl check cluster
所有实例数据库状态
srvctl status database -d bivardb
检查单个实例状态
srvctl status instance -d bivardb -i bivardb1
节点应用程序状态
srvctl status nodeapps
列出所有的配置数据库
srvctl config database
数据库配置
srvctl config database -d bivardb -a
ASM状态以及ASM配置
srvctl status asm
ASM磁盘组使用状态
asmcmd
ASMCMD> lsdg
TNS监听器状态以及配置
srvctl status listener
SCAN状态
srvctl status scan
VIP各个节点的状态
srvctl status vip -n bivardb1
srvctl status vip -n bivardb2
节点应用程序配置 —(VIP、GSD、ONS、监听器)
srvctl config nodeapps -a -g -s -l
验证所有集群节点间的时钟同步
cluvfy comp clocksync -verbose
集群中所有正在运行的实例 — (SQL):
SELECT inst_id , instance_number inst_no , instance_name inst_name , parallel , status ,database_status db_status , active_state state , host_name host FROM gv$instance ORDER BY inst_id;
启动和停止集群
以下操作需用root用户执行。
在本地服务器上停止Oracle Clusterware 系统:
$GRID_HOME/bin/crsctl stop cluster
注:在运行“crsctl stop cluster”命令之后,如果 Oracle Clusterware管理的资源中有任何一个还在运行,则整个命令失败。使用 -f 选项无条件地停止所有资源并停止 Oracle Clusterware 系统。
另请注意,可通过指定 -all 选项在集群中所有服务器上停止 Oracle Clusterware系统。
oracle用户修改密码过期时间
1、查看当前open用户
select username,account_status,expiry_date,profile from dba_users;
2、查看目前的密码过期策略
select * from dba_profiles s where s.profile='DEFAULT' and resource_name='PASSWORD_LIFE_TIME';
3、修改密码过期策略
alter profile default limit password_life_time unlimited;
4、过期的账户,重置密码后期不会再过期
$sqlplus / as sysdba
alter user smsc identified by <原来的密码> ----不用换新密码
########基础#############
#查看SQL
SELECT SQL_ID,SQL_TEXT, LAST_ACTIVE_TIME,SQL_FULLTEXT FROM v$sql ORDER BY LAST_ACTIVE_TIME;
#定位用户、IP
select user_id,machine from dba_hist_active_sess_history where t.sql_id='*******';
##Oracle数据库版本
select * from v$version where rownum=1;
#Oracle 身份认证
$ORACLE_HOME/network/admin/sqlnet.ora
#OS+密码
SQLNET.AUTHENTICATION_SERVICES = (ALL)
#密码
SQLNET.AUTHENTICATION_SERVICES = (NONE)
当不存在sqlnet.ora文件时,linux中可以正常登录,win中不能
#查看数据库对象
select owner, object_type, status, count(*) count#
from all_objects
group by owner, object_type, status;
#修改时间格式
export NLS_DATE_FORMAT="YYYY-MM-DD hh24:mi:ss"
alter system set nls_date_format='YYYY-MM-DD hh24:mi:ss' scope=spfile;
#查看实例状态及数据库状态
select status from v$instance;
select open_mode from v$database;
#############################
set head on //输出域标题
set colsep' '; //-域输出分隔符
set echo on //设置运行命令是是否显示语句
set feedback on; //设置显示“已选择XX行”
set heading off; //输出域标题,缺省为on
set pagesize 0; //输出每页行数,缺省为24,为了避免分页,可设定为0。
set linesize 80; //输出一行字符个数,缺省为80
set numwidth 12; //输出number类型域长度,缺省为10
set termout off; //显示脚本中的命令的执行结果,缺省为on
set trimout on; //去除标准输出每行的拖尾空格,缺省为off
set trimspool on; //去除重定向(spool)输出每行的拖尾空格,缺省为off
set serveroutput on; //设置允许显示输出类似dbms_output
set timing on; //设置显示“已用时间:XXXX”
set autotrace on; //设置允许对执行的sql进行分析
-数据文件位置
select * FROM dba_data_files;
--数据文件位置2
select * from v$datafile;
--查看控制文件
select * from v$controlfile;
--查看归档日志文件
select * from v$archived_log;
--查看闪回文件位置
select * from v$flashback_database_logfile;
#show full processlist
SELECT a.username,a.machine, b.sql_id, b.SQL_FULLTEXT
FROM v$session a, v$sqlarea b
WHERE a.sql_address = b.address
AND a.SQL_HASH_VALUE = b.HASH_VALUE;
#删除指定用户的所有表
begin
for droptable in
(select targettablename dt from tb_sys_syncdetail@center120 where targettablename in (select table_name from all_tables where owner='FH4')) loop
execute immediate 'drop table '||droptable.dt;
end loop;
end;
#实现列值自动增长触发器:
create sequence tb_gos_dzsw_order_pk
create or replace trigger dzsw_trigger
before insert on tb_gos_dzsw_ordersum
for each row
declare
tempnum number;
begin
select tb_gos_dzsw_order_pk.nextval into tempnum from dual;
:new.pk :=tempnum;
end;
#判断是否为数字:
CREATE OR REPLACE FUNCTION is_number(parmin VARCHAR2) RETURN NUMBER IS
val NUMBER;
BEGIN
val := TO_NUMBER(NVL(parmin, 'a'));
RETURN 1;
EXCEPTION
WHEN OTHERS THEN
RETURN 0;
END;
#判断是否为日期的函数
CREATE OR REPLACE FUNCTION is_date(parmin VARCHAR2) RETURN NUMBER IS
val DATE;
BEGIN
val := TO_DATE(NVL(parmin, 'a'), 'yyyy-mm-dd hh24:mi:ss');
RETURN 1;
EXCEPTION
WHEN OTHERS THEN
RETURN 0;
END;
#在函数或过程中加锁
declare
p_BranchID varchar2(20);
p_BillType varchar2(20);
v_lockid number;
v_result number;
begin
select branchid into p_BranchID from tb_common_billcode where branchid='FDG' and billtype='TAP';
select billtype into p_BillType from tb_common_billcode where branchid='FDG' and billtype='TAP';
v_lockid := dbms_utility.get_hash_value(p_BranchID||p_BillType, 0, 65535);
v_result := dbms_lock.request(id => v_lockid , lockmode => dbms_lock.x_mode, release_on_commit => TRUE);
dbms_output.put_line(v_lockid);
dbms_output.put_line( v_result);
dbms_output.put_line(p_BranchID||p_BillType);
v_result := dbms_lock.release(id => v_lockid);
dbms_output.put_line(' result ' || v_result);
end;
########性能#############
#查看影响性能的sql
select * from v$sql t where service='branch' and last_load_time >='2010-07-06' and last_active_time >to_date('2010-07-06','yyyy-mm-dd') order by t.USER_IO_WAIT_TIME desc,t.CPU_TIME desc
#查看Db_cache_size命中率
SELECT name,value FROM V$sysstat WHERE name in ('dbblock gets','consistent gets','physical reads');
查询结果命中率=1-physical reads/(dbblock gets+consistent gets)
#查看Shared_pool_size命中率
SELECT (1-(SUM(getmisses)/(SUM(gets)+SUM(getmisses))))*100 FROM V$rowcache;
########用户#############
#查看一个用户下的所有表,索引,存储过程的ddl
SELECT DBMS_METADATA.GET_DDL(U.OBJECT_TYPE, u.object_name) FROM USER_OBJECTS u where U.OBJECT_TYPE IN ('TABLE','INDEX','PROCEDURE');
#查看所有创建用户的ddl
SELECT DBMS_METADATA.GET_DDL('USER',U.username) FROM DBA_USERS U;
#锁定用户
alter user perf_test account lock;
#解锁用户
alter user perf_test account unlock;
#过期用户
alter user perf_test password expire;
#查看用户的proifle是哪个,一般是default:
SELECT username,PROFILE FROM dba_users;
#查看指定概要文件(如default)的密码有效期设置:
SELECT * FROM dba_profiles s WHERE s.profile='DEFAULT' AND resource_name='PASSWORD_LIFE_TIME';
#将密码有效期由默认的180天修改成“无限制”:
ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;
#用户和表空间的对应关系
select username,default_tablespace,temporary_tablespace from dba_users;
#删除了user,只是删除了该user下的schema objects,是不会删除相应的tablespace的。
drop user username cascade
########连接#############
#查看会话SID
select sid from v$mystat where rownum=1;
select userenv('sid') from dual;
#查看所有session(sid,serial#)
select * from v$session where username is not null;
#各用户session汇总
select username,count(username) from v$session where username is not null group by username
#杀会话
select sid,serial#,username from v$session where username is not null;
alter system kill session 'sid,serial#';
select 'alter system kill session '''||sid||','||SERIAL#||',@1'' immediate;' from gv$session where
#当前连接数
select count(*) from v$process;
#查看连接数参数的设置情况
select value from v$parameter where name = 'processes';
#并发连接数
Select count(*) from v$session where status='ACTIVE';
#查询数据库最大连接数
select value from v$parameter where name = 'processes';
#修改最大连接数
alter system set processes = 1000 scope = spfile;
shutdown immediate;
startup
########锁#############
#查看死锁与解锁
查看死锁
SELECT l.session_id sid,
s.serial#,
l.locked_mode,
l.oracle_username,
l.os_user_name,
s.machine,
s.terminal,
o.object_name,
s.logon_time
FROM v$locked_object l, all_objects o, v$session s
WHERE l.object_id = o.object_id
AND l.session_id = s.sid
ORDER BY sid, s.serial#;
解锁:
alter system kill session 'sid,serial#'; --结合上面查询死锁结果使用
########阻塞#############
#查看哪些表被锁住
select b.owner,b.object_name,a.session_id,a.locked_mode
from v$locked_object a,dba_objects b
where b.object_id = a.object_id;
select b.username,b.sid,b.serial#,logon_time
from v$locked_object a,v$session b
where a.session_id = b.sid order by b.logon_time;
#查看session:
select * from v$session where username is not null
select username,count(username) from v$session where username is not null group by username
#当前连接数:
select count(*) from v$process
#查看连接数参数的设置情况
select value from v$parameter where name = 'processes'
#并发连接数
Select count(*) from v$session where status='ACTIVE'
#查哪个过程被锁
SELECT * FROM V$DB_OBJECT_CACHE WHERE OWNER='过程的所属用户' AND CLOCKS!='0';
#查是哪一个SID,通过SID可知道是哪个SESSION.
SELECT * FROM V$ACCESS WHERE OWNER='过程的所属用户' AND NAME='刚才查到的过程名';
#查看等待事件为行锁的session
select a.snap_id,
a.sql_id,
a.session_id,
a.session_serial#,
a.blocking_session,
a.blocking_session_serial#,
a.blocking_session_status
from DBA_HIST_ACTIVE_SESS_HISTORY a
where event like '%enq: TX - row lock contention%'
and snap_id between 20399 and 20400
#查看阻塞回话,并统计阻塞次数
select a.blocking_session,
a.blocking_session_serial#,
count(a.blocking_session)
from DBA_HIST_ACTIVE_SESS_HISTORY a
where event like '%enq: TX - row lock contention%'
and snap_id between 20399 and 20400
group by a.blocking_session, a.blocking_session_serial#
order by 3 desc
#查看阻塞回话的sql_id和被阻塞的sql_id,条件为阻塞大于19次的
select distinct b.sql_id,c.blocked_sql_id
from DBA_HIST_ACTIVE_SESS_HISTORY b,
(select a.sql_id as blocked_sql_id,
a.blocking_session,
a.blocking_session_serial#,
count(a.blocking_session)
from DBA_HIST_ACTIVE_SESS_HISTORY a
where event like '%enq: TX - row lock contention%'
and snap_id between 20399 and 20400
group by a.blocking_session, a.blocking_session_serial#,a.sql_id
having count(a.blocking_session) > 19
order by 3 desc) c
where b.session_id = c.blocking_session
and b.session_serial# = c.blocking_session_serial#
and b.snap_id between 20399 and 20400
################表空间################################
#oracle用户权限、表空间
create user perf_test identified by password;
grant dba to perf_test;
create tablespace perf_test datafile '/data/oracle/oradata/orcl/perf_test.dbf' size 1024m;
ALTER DATABASE DATAFILE '/data/oracle/oradata/orcl/perf_test.dbf' AUTOEXTEND ON NEXT 100M MAXSIZE 2048M;
create temporary tablespace perf_test_tmp tempfile '/data/oracle/oradata/orcl/perf_test_tmp.dbf' size 50m autoextend on next 50m maxsize 1024m extent management local;
alter user perf_test default tablespace perf_test temporary tablespace perf_test_tmp;
alter tablespace perf_test add datafile '/data/oracle/oradata/orcl/perf_test2.dbf' size 1024m;
--删除空的表空间,但是不包含物理文件
drop tablespace tablespace_name;
--删除非空表空间,但是不包含物理文件
drop tablespace tablespace_name including contents;
--删除空表空间,包含物理文件
drop tablespace tablespace_name including datafiles;
--删除非空表空间,包含物理文件
drop tablespace tablespace_name including contents and datafiles;
--如果其他表空间中的表有外键等约束关联到了本表空间中的表的字段,就要加上CASCADE CONSTRAINTS
drop tablespace tablespace_name including contents and datafiles CASCADE CONSTRAINTS;
#删除表空间前已删除数据文件解决方法
shutdown abort // abort 中止 (强制中止)
startup mount
alter database datafile 'filename' offline drop;
alter database open;
drop tablespBace tablespace_name including contents;
#回收表未使用空间
alter table 表名 deallocate unused
##表空间
oracle中用户的所有数据都是存放在表空间中的,很多个用户可以共用一个表空间,也可以指定一个用户只用某一个表空间。
表空间:创建表空间会在物理磁盘上建立一个数据文件,作为数据库对象(用户、表、存储过程等等)的物理存储空间;
System表空间
SYSTEM表空间主要存放SYS用户的各个对象和其他用户的少量对象
SYSAUX表空间
SYSTEM表空间主要用于存放Oracle系统内部的数据字典,而SYSAUX表空间则充当SYSTEM表空间
的辅助表空间,主要用于存储数据字典以外的其他数据对象,它在一定程度上降低了SYSTEM表空
users表空间
用户:创建用户必须为其指定表空间,如果没有显性指定默认表空间,则指定为users表空间;创建用户后,可以在用户上,创建表、存储过程等等其他数据库对象;
#查看所有表空间的ddl语句
SELECT DBMS_METADATA.GET_DDL('TABLESPACE', TS.tablespace_name) FROM DBA_TABLESPACES TS;
#查看表类型
select table_name, tablespace_name, blocks, num_rows fromuser_tables where table_name in ('T_IOT','T_HEAP');
#查看表对应的表空间
SELECT TABLE_NAME,TABLESPACE_NAME FROM DBA_TABLES WHERE TABLE_NAME='TEST1';
#查询表空间对应的文件
select tablespace_name,file_id,bytes/1024/1024,file_name from dba_data_files order by file_id;
#查看表空间大小:
select tablespace_name, file_id, file_name,round(bytes/(1024*1024),0) total_space
from dba_data_files
order by tablespace_name;
#查看临时表空间大小
select name,to_char(bytes/1024/1024)||'M' from v$tempfile;
#查看表空间统计量:
SELECT a.tablespace_name AS "表空间名", b.total AS "表空间大小", a.free AS "表空间剩余大小", total - free AS "表空间使用大小"
, total / (1024 * 1024 * 1024) AS "表空间大小(G)"
, free / (1024 * 1024 * 1024) AS "表空间剩余大小(G)"
, (total - free) / (1024 * 1024 * 1024) AS "表空间使用大小(G)"
, round((total - free) / total, 4) * 100 AS "使用率 %"
FROM (
SELECT tablespace_name, SUM(bytes) AS free
FROM dba_free_space
GROUP BY tablespace_name
) a, (
SELECT tablespace_name, SUM(bytes) AS total
FROM dba_data_files
GROUP BY tablespace_name
) b
WHERE a.tablespace_name = b.tablespace_name
AND a.tablespace_name = 'perf_test';
#查看表空间是否具有自动扩展的能力
SELECT T.TABLESPACE_NAME,D.FILE_NAME,
D.AUTOEXTENSIBLE,D.BYTES,D.MAXBYTES,D.STATUS
FROM DBA_TABLESPACES T,DBA_DATA_FILES D
WHERE T.TABLESPACE_NAME =D.TABLESPACE_NAME
ORDER BY TABLESPACE_NAME,FILE_NAME;
################################备份恢复################################
#rman备份恢复
使用RMAN-cmd运行
rman target /
显示rman配置:
show all;
report schema 报告目标数据库的物理结构;
report need backup days=3; 报告最近3天没有被备份的数据文件;
report need backup days 3 tablespace users; 在USERS表空间上3天未备份的数据文件;
report need backup incremental 3; 报告恢复数据文件需要的增量备份个数超过3次的数据文件;
report need backup redundancy 2 database; 报告备份文件低于2份的所有数据文件;
report need backup redundancy=2;
report need backup recovery window of 6 days; 报告文件报表的恢复需要超过6天的归档日志的数据文件;
report unrecoverable; 报告数据库所有不可恢复的数据文件;
report obsolete redunndancy 2; 报告备份次数超过2次的陈旧备份;
report obsolete; 报告多余的备份;
list backup 列出详细备份;
list expired backup 列出过期备份;
list backup of database; 列出所有数据文件的备份集;
list backup of tablespace user01; 列出特定表空间的所有数据文件备份集;
list backup of controlfile 列出控制文件备份集;
list backup of archivelog all 列出归档日志备份集详细信息;
list archivelog all; 列出归档日志备份集简要信息
list backup of spfile 列出SPFILE备份集;
list copy of datafile 5 列出数据文件映像副本;
list copy of controlfile 列出控制文件映像副本;
list copy of archivelog all 列出归档日志映像副本;
list incarnation of database 列出对应物/列出数据库副本;
list backup summary; 概述可用的备份;
B表示backup
F表示FULL
A表示archive log
0 1表示incremental backup
S说明备份状态(A AVAILABLE X EXPIRED )
list backup by file 按备份类型列出备份;
crosscheck backup 核对所有备份集;
crosscheck backup of database 核对所有数据文件的备份集;
crosscheck backup of tablespace users 核对特定表空间的备份集;
crosscheck backup of datafile 4 核对特定数据文件的备份集;
crosscheck backup of controlfile 核对控制文件的备份集;
crosscheck backup of spfile 核对SPFILE的备份集;
crosscheck backup of archivelog sequence 3 核对归档日志的备份集;
crosscheck copy 核对所有映像副本;
crosscheck copy of database 核对所有数据文件的映像副本;
crosscheck copy of tablespace users 核对特定表空间的映像副本;
crosscheck copy of datafile 6 核对特定数据文件的映像副本;
crosscheck copy of archivelog sequence 4 核对归档日志的映像副本;
crosscheck copy of controlfile 核对控制文件的映像副本;
crosscheck backup tag='SAT_BACKUP';
crosscheck backup completed after 'sysdate - 2'
crosscheck backup completed between 'sysdate - 5' and 'sysdate -2 '
crosscheck backup device type sBT;
crosscheck archivelog all;
crosscheck archivelog like '%ARC00012.001'
crosscheck archivelog from sequence 12;
crosscheck archivelog until sequence 522;
delete obsolete; 删除陈旧备份;
delete expired backup; 删除EXPIRED备份
delete expired copy; 删除EXPIRED副本;
delete backupset 19; 删除特定备份集;
delete backuppiece ''d:backupDEMO_19.bak'' 删除特定备份片;
delete backup 删除所有备份集;
delete datafilecopy ''d:backupDEMO_19.bak'' 删除特定映像副本;
delete copy 删除所有映像副本;
backup archivelog all delete input;
backup backupset 22 format = ''d:backup%u.bak'' delete input
delete backupset id; 删除备份集
二,备份查询
list backup; 备份集列表【归档日志文件、数据文件、spfile、control file】
report obsolete; 用于列出rman资料库中能够被删除的全备份、数据文件拷贝和归档日志记录。
三,删除备份
delete backupset;
二,完全备份
一,备份数据库
一,非一致性备份
backup database format 'G:\\oradb_%Y_%M_%D_%U.bak' //备份
sql 'alter system archive log current'; //对当前的联机重做日志归档
list backup; //查询
二,一致性备份
shutdown immediate
startup mount
backup database format '\\oradb_%Y_%M_%D_%U.bak'
alter database open;
二,备份表空间
run
allocate channel ch1 type disk;
backup tablespace shao
format 'G:\\%d_%p_%t_%c.dbf';
三,备份数据文件
backup datafile 1,2,3 filesperset 3;
四,备份控制文件
backup current controlfile
或
backup tablespace shao include current controlfile;
五,备份日志文件
backup archivelog all
二,增量备份
级别 说明
0 全备份
1 上次0级备份或1级至今的增量(不管2级备份)
2 上次无论任何备份到至今的增量
一,0级差异备份
run
allocate channel ch_1 type disk;
backup incremental level=0
format 'G:\\oar11g.bak'
tablespace system,sysaux,users;
二,1级差异备份
run
allocate channel ch_1 type disk;
backup incremental level=1
format 'G:\\oar11g.bak'
tablespace system,sysaux,users;
三,2级备份
run
allocate channel ch_1 type disk;
backup incremental level=2
format 'G:\\oar11g.bak'
tablespace system,sysaux,users;
三,恢复
一,完全恢复
在mount状态下
run
allocate channel ch1 disk;
restore database;
recover database;
二,基于时间的不完全恢复
一,备份数据库
二,查询当前时间
select sysdate from dual;
三,模拟错误-删除数据
四,恢复-mount模式
run
sql'alter session set date_format="YYYY-MM-DD HH24:MI:SS"';
allocate channel ch1 type disk;
allocate channel ch2 type disk;
set until time '2019-05-16 9:30:00';
restore database;
recover database;
sql'alter database open resetlogs';
################################字符集################################
#oracle server 端 字符集查询
select userenv('language') from dual;
#查询oracle client端的字符集
echo $NLS_LANG
#修改server端字符集
shutdown immediate;
startup mount;
alter system enable restricted session;
alter system set job_queue_processes=0;
alter system set aq_tm_processes=0;
alter database open;
alter database character set internal_use ZHS16GBK;
shutdown immediate;
startup;
################################表################################
#查看某用户所有表
select * from all_tables where owner='perf_test';
#查看表大小
select sum(bytes)/(1024*1024) as "size(M)" from user_segments where segment_name=upper('test');
#查看表创建时间
select object_name,created from user_objects where object_name=upper('test');
#生成执行计划
explain plan for select * from test where id = 2;
#查看执行计划
select * from table(dbms_xplan.display);
#查询一张表里面索引
select * from user_indexes where table_name=upper('test');
select * from ALL_INDEXES where table_name=upper('tt');
#查询索引信息
select * from user_ind_columns where index_name=upper('idx_classid');
#查看索引大小
select sum(bytes)/(1024*1024) as "size(M)" from user_segments where segment_name=upper('idx_classid');
#表压缩的方法
alter table test move COMPRESS;
################################日志################################
#修改INIT.ORA文件参数
alter system set undo_tablespace=undotbs2 scope=spfile;
alter system set undo_management=auto scope=spfile;
#启用/关闭 归档日志(archive log)
#开启归档日志
shutdown immediate;
startup mount;
alter database archivelog; -- 开启归档日志
alter database open; -- 开启数据库
archive log list; --查看归档日志状态
#关闭归档日志
shutdown immediate;
startup mount;
alter database noarchivelog;
alter database open;
archive log list;
--干净的关闭数据库
SQL> shutdown immediate
--以mount模式启动
SQL> startup mount
--切换到归档模式
SQL> alter database archivelog;
--开启强制日志
SQL> alter database force logging;
--打开数据库
SQL> alter database open;
--查看归档
SQL> archive log list;
--查看是否为强制日志
SQL> select force_logging from v$database;
--查看Redo和Standby Redo
SQL> select * from v$logfile;
--仅仅显示Online Redo,不显示Standby Redo
SQL> select * from v$log;
#查看Standby Redo Log
SELECT GROUP#, BYTES/1024/1024 M FROM V$STANDBY_LOG;
################################EM################################
#oem
设置好监听器, 启动监听:lsnrctl start,查看监听状态:lsnrctl statu
删除dbcontrol:emca -deconfig dbcontrol db
删除EM资料库:emca -repos drop
创建新资料库:emca -repos create
重新配置dbcontrol:emca -config dbcontrol db
#查看回滚段名称及大小
select segment_name,
tablespace_name,
r.status,
(initial_extent / 1024) initialextent,
(next_extent / 1024) nextextent,
max_extents,
v.curext curextent
from dba_rollback_segs r, v$rollstat v
where r.segment_id = v.usn(+)
order by segment_name;
#查看控制文件
select name from v$controlfile;
#查看日志文件
select member from v$logfile;
###################################################################################################################################################################################################################################################################################################
(一) 表空间类
1. 表空间使用情况
set linesize 200
set pagesize 2000
set time on
set timing on
col tablespace_name for a25
SELECT df.tablespace_name, COUNT (*) datafile_count,
ROUND (SUM (df.BYTES) / 1048576/1024,2) size_gb,
ROUND (SUM (free.BYTES) / 1048576/1024,2) free_gb,
ROUND (SUM (df.BYTES) / 1048576/1024 - SUM (free.BYTES) / 1048576/1024,2) used_gb,
ROUND (MAX (free.maxbytes) / 1048576/1024,2) maxfree,
100 - ROUND (100.0 * SUM (free.BYTES) / SUM (df.BYTES), 2) pct_used,
ROUND (100.0 * SUM (free.BYTES) / SUM (df.BYTES), 2) pct_free
FROM dba_data_files df,
(SELECT tablespace_name, file_id, SUM (BYTES) BYTES, MAX (BYTES) maxbytes
FROM dba_free_space
where bytes > 1024 * 1024
GROUP BY tablespace_name, file_id) free
WHERE df.tablespace_name = free.tablespace_name(+) AND df.file_id = free.file_id(+)
--and df.tablespace_name LIKE 'QRY_576'
GROUP BY df.tablespace_name
--having ROUND (SUM (free.BYTES) / 1048576, 2)<2000
ORDER BY 8;
/
2. 表空间中占用空间大的段
select owner,segment_name,sum(bytes)/1024/1024/1024 gbytes
from dba_segments
where tablespace_name='PRECISE_PW_TAB_MEDIUM'
group by owner,segment_name
having sum(bytes)/1024/1024/1024>1
order by 3 desc;
3. undo表空间使用情况
(如果used_rag>60%需要查具体是哪个进程)
set linesize 200
col used_pct format a8
select b.tablespace_name,
nvl(used_undo,0) "USED_UNDO(M)",
total_undo "Total_undo(M)",
trunc(nvl(used_undo,0) / total_undo * 100, 2) || '%' used_PCT
from (select nvl(sum(bytes / 1024 / 1024), 0) used_undo, tablespace_name
from dba_undo_extents
where status = 'ACTIVE'
group by tablespace_name) a,
(select tablespace_name, sum(bytes / 1024 / 1024) total_undo
from dba_data_files
where tablespace_name in
(select value
from v$spparameter
where name = 'undo_tablespace'
and (sid = (select instance_name from v$instance) or
sid = '*'))
group by tablespace_name) b
where a.tablespace_name (+)= b.tablespace_name
/
--注:包含UNEXPIRED类型 (主要是用这个)
select b.tablespace_name,
nvl(used_undo,0) "USED_UNDO(M)",
total_undo "Total_undo(M)",
trunc(nvl(used_undo,0) / total_undo * 100, 2) || '%' used_PCT
from (select nvl(sum(bytes / 1024 / 1024), 0) used_undo, tablespace_name
from dba_undo_extents
where status in ( 'ACTIVE','UNEXPIRED')
group by tablespace_name) a,
(select tablespace_name, sum(bytes / 1024 / 1024) total_undo
from dba_data_files
where tablespace_name in
(select value
from v$spparameter
where name = 'undo_tablespace'
and (sid = (select instance_name from v$instance) or
sid = '*'))
group by tablespace_name) b
where a.tablespace_name (+)= b.tablespace_name
/
select tablespace_name,status,sum(bytes)/1024/1024 MB from dba_undo_extents
where tablespace_name like 'UNDOTBS%'
group by tablespace_name,status
order by 1
/
4. 各个session使用的undo
SELECT r.name rbs,
nvl(s.username, 'None') oracle_user,
s.osuser client_user,
p.username unix_user,
s.sid,
s.serial#,
p.spid unix_pid,
t.used_ublk * TO_NUMBER(x.value) / 1024 / 1024 as undo_mb ,
TO_CHAR(s.logon_time, 'mm/dd/yy hh24:mi:ss') as login_time,
TO_CHAR(sysdate - (s.last_call_et) / 86400, 'mm/dd/yy hh24:mi:ss') as last_txn,
t.START_TIME transaction_starttime
FROM v$process p,
v$rollname r,
v$session s,
v$transaction t,
v$parameter x
WHERE s.taddr = t.addr
AND s.paddr = p.addr
AND r.usn = t.xidusn(+)
AND x.name = 'db_block_size'
ORDER by undo_mb desc
/
5. TEMP表空间使用情况
----RAC
SELECT inst_id, A.tablespace_name tablespace,
D.mb_total,
SUM(A.used_blocks * D.block_size) / 1024 / 1024 mb_used,
D.mb_total - SUM(A.used_blocks * D.block_size) / 1024 / 1024 mb_free
FROM gv$sort_segment A,
(SELECT B.name, C.block_size, SUM(C.bytes) / 1024 / 1024 mb_total
FROM v$tablespace B, v$tempfile C
WHERE B.ts# = C.ts#
GROUP BY B.name, C.block_size) D
WHERE A.tablespace_name = D.name
GROUP by inst_id,A.tablespace_name, D.mb_total;
----单节点
SELECT A.tablespace_name tablespace,
D.mb_total,
SUM(A.used_blocks * D.block_size) / 1024 / 1024 mb_used,
D.mb_total - SUM(A.used_blocks * D.block_size) / 1024 / 1024 mb_free
FROM v$sort_segment A,
(SELECT B.name, C.block_size, SUM(C.bytes) / 1024 / 1024 mb_total
FROM v$tablespace B, v$tempfile C
WHERE B.ts# = C.ts#
GROUP BY B.name, C.block_size) D
WHERE A.tablespace_name = D.name
GROUP by A.tablespace_name, D.mb_total;
6. 各个session使用的 TEMP 段
----a.
SELECT S.sid || ',' || S.serial# sid_serial,
S.username,
S.osuser,
P.spid,
S.module,
S.program,
SUM(T.blocks) * TBS.block_size / 1024/1024 mb_used,
T.tablespace,
COUNT(*) sort_ops
FROM v$sort_usage T, v$session S, dba_tablespaces TBS, v$process P
WHERE T.session_addr = S.saddr
AND S.paddr = P.addr
AND T.tablespace = TBS.tablespace_name
GROUP BY S.sid,
S.serial#,
S.username,
S.osuser,
P.spid,
S.module,
S.program,
TBS.block_size,
T.tablespace
ORDER BY sid_serial;
select a.username,
a.sql_id,
a.SEGTYPE,
b.BYTES_USED/1024/1024/1024||'G',
b.BYTES_FREE/1024/1024/1024 from V$TEMPSEG_USAGE a join V$TEMP_SPACE_HEADER b on a.TABLESPACE=b.tablespace_name;
----b.
SELECT S.sid || ',' || S.serial# sid_serial,
S.username,
T.blocks * TBS.block_size / 1024 / 1024 mb_used,
T.tablespace,
T.sqladdr address,
Q.hash_value,
Q.sql_text
FROM v$sort_usage T, v$session S, v$sqlarea Q, dba_tablespaces TBS
WHERE T.session_addr = S.saddr
AND T.sqladdr = Q.address(+)
AND T.tablespace = TBS.tablespace_name
ORDER BY S.sid;
(二) Session信息与等待事件
1. 某个session的信息
select nvl(s.username, 'None') oracle_user,
s.logon_time,
p.username unix_user,
s.sid,
s.serial#,
p.spid unix_pid,
s.status,
s.process,
s.osuser,
s.program,
s.module,
s.machine,
s.event,
-- TO_CHAR(sysdate - (s.last_call_et) / 86400, 'mm/dd/yy hh24:mi:ss') as last_txn,
l.SQL_TEXT,
s.sql_id,
s.prev_sql_id
from v$process p, v$session s, v$sql l
where s.paddr = p.addr
and s.SQL_ADDRESS = l.ADDRESS(+)
and s.SQL_HASH_VALUE = l.HASH_VALUE(+)
and s.sql_child_number = l.child_number(+)
and s.sid = '8926';
1、分析listener log中每个IP的连接数
grep '13-JUL-2011 14:' listener.log |awk 'print $1,$2,$6'|awk -F":" 'print $1,":",$2'|sort -n|uniq -c
2、分析listener log中每秒的连接数,如果没有egrep的系统请使用grep –E以使用正则表达式
egrep '28-MAY-2013 1[2-6]:[00-59]' listener_perf_testsdpb01.log1604 |awk 'print $1,$2,$6'|awk -F":" 'print $1,":",$2,":"$3'|awk 'print $1,$2$3$4$5'|sort -n|uniq -c
2. session,process的阀值,及历史情况
select *
from (SELECT resource_name,
current_utilization,
max_utilization,
initial_allocation,
limit_value,
round(max_utilization / initial_allocation, 2) * 100 pct
FROM V$RESOURCE_LIMIT
where resource_name in ('processes', 'sessions'))
where pct > 60;
3. 实例当前(活动)的关键信息
select to_char(a.logon_time, 'yyyy-mm-dd hh24:mi') logon_time,
a.sql_id,
a.event,
a.username,
a.osuser,
a.process,
a.machine,
a.program,
a.module,
b.sql_text,
b.LAST_LOAD_TIME,
to_char(b.last_active_time, 'yyyy-mm-dd hh24:mi:ss') last_active_time,
c.owner,
c.object_name,
a.last_call_et,
a.sid,
a.SQL_CHILD_NUMBER,
c.object_type,
p.PGA_ALLOC_MEM,
a.p1,
a.p2,
a.p3,
'kill -9 ' || p.spid killstr
from v$session a, v$sql b, dba_objects c, v$process p
where a.status = 'ACTIVE'
and a.wait_class <> 'Idle'
and p.addr = a.paddr
and a.sql_id = b.sql_id(+)
and a.sql_child_number = b.CHILD_NUMBER(+)
and a.row_wait_obj# = c.object_id(+)
and a.type = 'USER'
order by a.sql_id, a.event;
4. Session 等待事件
----a. RAC
select inst_id,event,count(*)
from gv$session
where wait_class <> 'Idle'
group by inst_id,event
order by count(*) desc;
----单节点
select event,count(*)
from v$session
where wait_class <> 'Idle'
group by event
order by count(*) desc;
select inst_id,sql_id,count(*),max(event),min(event),min(a.SQL_CHILD_NUMBER),max(a.SQL_CHILD_NUMBER)
from gv$session a
where wait_class <> 'Idle'
group by inst_id,sql_id
order by inst_id,count(*) desc;
----b.9i
select a.event,count(1)
from v$session_wait a,v$session b
where a.EVENT not in ('SQL*Net%', 'rdbms ipc message')
and a.sid=b.sid
and b.STATUS='ACTIVE'
group by a.event
order by count(1) desc;
5. 检查等待及堵塞事件
set lin 200
COL USERNAME FOR A15
COL EVENT FOR A50
COL SID FOR 999999
COL INST_ID FOR 99
select inst_id,sid, username, event, blocking_session,
seconds_in_wait, wait_time
from gv$session where state in ('WAITING')
and wait_class != 'Idle';
select inst_id,event, count(1)
from gv$session where wait_class != 'Idle'
group by inst_id,event
order by 1,3 desc
select event,sid,p1,p2,p3 from v$session_wait where event not like 'SQL*%' and event not like 'rdbms%';
-----rac环境:
select t.inst_id,t.EVENT,count(1) from gv$session_wait t
where t.wait_class != 'Idle'
group by t.inst_id,t.EVENT
having count(1)>5
order by 1,count(1) desc;
-----确定引起等待事件的sessin的sql的sid
col sid for 99999
col event for a30
col p1text for a10
col p2text for a10
select SID, EVENT, P1TEXT, P1RAW, P2TEXT, P2, SECONDS_IN_WAIT
from v$session_wait t
where t.EVENT='library cache lock'
order by 7
db file sequential read
select xidusn, object_id, session_id, locked_mode from v$locked_object order by 2,1
6. 过去某个时间段内的等待事件
SELECT *
FROM (SELECT a.program,
a.sql_id,
a.session_state,
a.event,
count(*),
lpad(round(ratio_to_report(count(*)) over() * 100) || '%',
10,
' ') percent,
MIN(a.sample_time),
MAX(a.sample_time)
FROM v$active_session_history a
WHERE a.sample_time BETWEEN
to_date('20191011 16:00:00', 'YYYYMMDD HH24:MI:SS') AND
to_date('20191011 0:00:00', 'YYYYMMDD HH24:MI:SS')
GROUP BY a.program, a.sql_id, a.session_state, a.event
ORDER BY percent DESC)
WHERE ROWNUM <= 10
SELECT *
FROM (SELECT a.program,
a.sql_id,
a.session_state,
a.event,
count(*),
lpad(round(ratio_to_report(count(*)) over() * 100) || '%',
10,
' ') percent,
MIN(a.sample_time),
MAX(a.sample_time)
FROM dba_hist_active_sess_history a
WHERE a.sample_time BETWEEN
to_date('20130121 10:00:00', 'YYYYMMDD HH24:MI:SS') AND
to_date('20130121 11:00:00', 'YYYYMMDD HH24:MI:SS')
GROUP BY a.program, a.sql_id, a.session_state, a.event
ORDER BY percent DESC)
WHERE ROWNUM <= 30
7. library cache pin和library cache lock
select s.sid, s.program, s.machine
from x$kglpn p, v$session s
where p.kglpnuse = s.saddr(+)
and p.kglpnmod <> 0
and kglpnhdl in
(select p1raw
from v$session_wait
where event in ('library cache pin', 'library cache lock',
'library cache load lock'));
select s.sid, kglpnmod "mode", kglpnreq "req"
from x$kglpn p, v$session s
where p.kglpnuse = s.saddr
and kglpnhdl = 'c000000d1f6864a8';
8. latch free
9. P1TEXT :name|mode 转化为锁类型和模式
SELECT chr(bitand(141479102, -16777216) / 16777215) ||
chr(bitand(141479102, 16711680) / 65535) Type,
mod(141479102, 16) lmode
from DUAL;
10. cursor: Cursor: pin S wait on X等待的信息
select b.*, sq.sql_text
from v$session se,
v$sql sq,
(select a.*, s.sql_text
from v$sql s,
(select sid,
event,
wait_class,
p1,
p2raw,
to_number(substr(p2raw, 1, 4), 'xxxx') sid_hold_mutex_x
from v$session_wait
where event like 'cursor%') a
where s.HASH_VALUE = a.p1) b
where se.sid = b.sid
and se.sql_hash_value = sq.hash_value;
11. buffer busy wait
12. latch: cache buffers chains
13. 其他常见等待事件
(三) Sql与执行计
1. 慢SQL
SQL有关的视图:v$sql v$sqltext v$sqlarea v$sqlstat v$sql_plan
----执行时间最长的SQL
select * from (
select sa.SQL_ID,sa.EXECUTIONS,sa.ELAPSED_TIME, sa.COMMAND_TYPE from v$sqlarea sa where sa.EXECUTIONS > 0 order by (sa.ELAPSED_TIME/sa.EXECUTIONS) desc
) where rownum <= 10;
----根据sql_id查SQL语句
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR('SQL_ID',SQL_CHILD_NUMBER));
1、select sql_text from v$sqltext a where sql_id = 'ayhdtkhabjxt6' order by piece asc;
alter session set statistics_level=all;
set timing on
set long 999999999
set linesize 10000 pagesize 5000
col SQL_FULLTEXT for a200
col SQL_TEXT for a150
2、select SQL_ID, SQL_TEXT
from DBA_HIST_SQLTEXT
where sql_ID in ('6y6ak88tmb45p') ;
----根据sid查SQL语句
select sql_text from v$sqltext a where a.hash_value = (select sql_hash_value from v$session b where b.sid = '&sid' )
order by piece asc
-----SQL执行耗时
select a.sql_text SQL语句,
b.etime 执行耗时,
c.user_id 用户ID,
c.SAMPLE_TIME 执行时间,
c.INSTANCE_NUMBER 实例数,
u.username 用户名, a.sql_id SQL编号
from dba_hist_sqltext a,
(select sql_id, ELAPSED_TIME_DELTA / 1000000 as etime
from dba_hist_sqlstat
where ELAPSED_TIME_DELTA / 1000000 >= 1) b,
dba_hist_active_sess_history c,
dba_users u
where a.sql_id = b.sql_id
and u.username = 'MYDB'
and c.user_id = u.user_id
and b.sql_id = c.sql_id
and a.sql_text like '%select * from big_data_tbl%'
order by SAMPLE_TIME desc,
b.etime desc;
2. 查看SQL执行用户
select USERNAME from DBA_HIST_ACTIVE_SESS_HISTORY s
join dba_users u
on s.USER_ID = u.USER_ID
where SQL_ID = '9u33wjgkfswfg'
and s.USER_ID is not null
and rownum = 1;
3. 长时间运行SQL
select sid,
serial#,
username,
opname,
target,
round(totalwork * 8 / 1024, 0) || 'MB' table_size,
round(sofar / totalwork * 100) || '%' pct,
start_time,
time_remaining,
elapsed_seconds,
sql_hash_value
from v$session_longops;
4. 没有使用绑定变量的SQL
Select hash_value, substr(sql_text,1,80)
from v$sqlarea
where substr(sql_text,1,40) in (select substr(sql_text,1,40)
from v$sqlarea
having count(*) > 4
group by substr(sql_text,1,40))
order by sql_text;
5. 获取 SQL_PLAN
(执行计划的方法,多种)
----a.
set autotrace on
---b.
explain plan for ..
---c.
sql_trace(session or system level)
---d.
10046 event(session or system level)
---E
.第二个参数为 sql_child_number
select * from table(dbms_xplan.display_cursor('62hxa8afhn5js',''));
---f.历史
select sql_id,
plan_hash_value,
a.DEPTH,
lpad(operation,
a.DEPTH + length(operation) +
decode(a.PARENT_ID, null, 0, a.PARENT_ID))||decode(options,null,null,'('||options||')') operation,
object_name,cost,CARDINALITY,bytes,
to_char(a.TIMESTAMP,'yyyy-mm-dd hh24:mi:ss') time
from dba_hist_sql_plan a
where sql_id = '901wzg6df1qyu'
order by a.plan_hash_value, a.DEPTH asc
----g.
select lpad(oper, length(oper) + level * 2, ' ') oper, cost
from (select object_name || ':' || operation || ' ' || options as oper,
cost,
id,
parent_id
from v$sql_plan
where hash_value = &hash_value
and address = '&address')
start with id = 0
connect by prior id = parent_id;
6. 获取 SQL 语句中绑定变量的值
select hash_value,
sql_id,
name,
datatype_string,
value_string,
was_captured,
last_captured,
position
from v$sql_bind_capture
where sql_id = '1s397f81jvsb8';
7. 获取SQL PLAN的变化时间
select sql_id,
plan_hash_value,
id,
operation,
options,
object_owner,
object_name,
depth,
cost,
timestamp
from DBA_HIST_SQL_PLAN
where sql_id = '8n5smw4zwb8rd'
order by 2, 3;
8. SQL的执行效率
select to_char(b.begin_interval_time, 'yyyy-mm-dd hh24:mi:ss') time,
a.sql_id,
a.plan_hash_value,
a.executions_delta executes,
round(a.buffer_gets_delta /
decode(nvl(a.executions_delta, 1), 0, 1, a.executions_delta),
0) per_buffer_gets,
round(a.cpu_time_delta /
decode(nvl(a.executions_delta, 1), 0, 1, a.executions_delta) / 1000 / 1000,
5) "per_cpu_time(s)",
round(a.elapsed_time_delta /
decode(nvl(a.executions_delta, 1), 0, 1, a.executions_delta) / 1000 / 1000,
5) "per_elapsed_time(s)",
round(a.rows_processed_delta /
decode(nvl(a.executions_delta, 1), 0, 1, a.executions_delta),
0) per_rows_processd,
a.module,
a.sorts_delta
from dba_hist_sqlstat a, dba_hist_snapshot b
where a.snap_id = b.snap_id
and a.sql_id in ('6qjp3gudk39s4')
and a.instance_number = b.instance_number
-- and a.plan_hash_value = 1455286942
and a.instance_number = 1
and (b.begin_interval_time >
to_date('2012-08-15 02:00:00', 'yyyy-mm-dd hh24:mi:ss') and
b.begin_interval_time <
to_date('2012-08-15 02:30:00', 'yyyy-mm-dd hh24:mi:ss'))
order by 1;
9. sql 语句使用的workarea情况,最好有快照
注: dbmon.mon_sql_workarea 为v$sql_workarea的人工快照采集表
select a.sql_id,
a.OPERATION_TYPE,
a.TOTAL_EXECUTIONS - b.TOTAL_EXECUTIONS,
a.OPTIMAL_EXECUTIONS - b.OPTIMAL_EXECUTIONS,
a.ONEPASS_EXECUTIONS,
a.LAST_MEMORY_USED,a.ESTIMATED_OPTIMAL_SIZE,
a.ONEPASS_EXECUTIONS-b.ONEPASS_EXECUTIONS
from (select a.sql_id,
OPERATION_TYPE,
TOTAL_EXECUTIONS,
OPTIMAL_EXECUTIONS,
ONEPASS_EXECUTIONS,
WORKAREA_ADDRESS,
LAST_MEMORY_USED,ESTIMATED_OPTIMAL_SIZE
from dbmon.mon_sql_workarea a
where time = to_date('2012-8-15 2:24:01', 'yyyy-mm-dd hh24:mi:ss')) a,
(select a.sql_id,
OPERATION_TYPE,
TOTAL_EXECUTIONS,
OPTIMAL_EXECUTIONS,
ONEPASS_EXECUTIONS,
WORKAREA_ADDRESS
from dbmon.mon_sql_workarea a
where time = to_date('2012-8-15 2:0:10', 'yyyy-mm-dd hh24:mi:ss')) b
where a.sql_id = b.sql_id
and a.WORKAREA_ADDRESS = b.WORKAREA_ADDRESS
and a.OPERATION_TYPE = b.OPERATION_TYPE
and a.TOTAL_EXECUTIONS - b.TOTAL_EXECUTIONS > 0
order by 3 desc
(四) 锁情况和解锁
1. 锁情况
SELECT DECODE(request, 0, 'Holder: ', 'Waiter: ') || SID sess,
decode(lmode,
0,
'none',
1,
'null',
2,
'row share',
3,
'row exclusive',
4,
'share',
5,
'share row exclusive',
6,
'exclusive') lmode,
ctime,
inst_id,
id1,
id2,
lmode,
request,
TYPE
FROM gV$LOCK
WHERE (id1, id2, TYPE) IN
(SELECT id1, id2, TYPE FROM gV$LOCK WHERE request > 0)
ORDER BY id1, request;
2. 解锁
select 'kill -9 ' || spid, 'ps -ef|grep ' || spid
from v$process p, v$session s
where p.addr = s.paddr
and s.sid In
(Select sid
From (select INST_ID,
SID,
TYPE,
ID1,
ID2,
LMODE,
REQUEST,
CTIME,
BLOCK
from gv$lock
where (ID1, ID2, TYPE) in
(select ID1, ID2, TYPE from gv$lock where request > 0)
order by ctime desc)
Where Block = 1 /*and inst_id=2*/);
select a.logon_time,
a.sql_id,
a.event,
a.username,
a.osuser,
a.process,
a.machine,
a.program,
a.module,
b.sql_text,
b.LAST_LOAD_TIME,
to_char(b.last_active_time, 'yyyy-mm-dd hh24:mi:ss') last_active_time,
c.owner,
c.object_name,
a.last_call_et,
a.sid,
a.SQL_CHILD_NUMBER,
c.object_type,
p.PGA_ALLOC_MEM,
a.BLOCKING_SESSION_STATUS,
'kill -9 ' || p.spid killstr
from v$session a, v$sql b, dba_objects c, v$process p
where a.wait_class <> 'Idle'
/* and a.status = 'ACTIVE'*/
and p.addr = a.paddr
and a.sql_id = b.sql_id(+)
and a.sql_child_number = b.CHILD_NUMBER(+)
and a.row_wait_obj# = c.object_id(+)
and a.type = 'USER'
and a.sid in (select distinct holding_session
from dba_waiters
where lock_type = 'Transaction')
order by a.sql_id, a.event;
(五) Kill进程与session
1. Kill LOCAL=NO进程
--Kill所有的外部链接
ps -ef|grep LOCAL=NO| awk 'print " kill -9 "$2' > k.out
sh k.out
ps -ef |grep LOCAL=NO|grep -v grep|cut -c 9-15|xargs kill -9
ps -ef |grep init.d|grep -v grep|cut -c 9-15|xargs kill -9
2. kill访问某对象的进程
SELECT 'kill -9 ' || SPID
FROM V$SESSION A,
V$PROCESS B,
(SELECT /*+RULE*/
SID
FROM V$ACCESS S
WHERE S.OBJECT = 'ACC_WOFF_BILL_01'
AND S.OWNER = 'ZIJIE') C
WHERE A.PADDR = B.ADDR
AND A.SID = C.SID
AND A.STATUS != 'KILLED';
3. Kill job进程
----如果是job的话需要和应用确认是否可以删除job.
如果是程序自动生成的job一般都可以删掉.
SELECT 'exec sys.dbms_ijob.remove(' || JOB || ');'
FROM DBA_JOBS_RUNNING D,
(SELECT /*+RULE*/
INST_ID, SID
FROM GV$ACCESS S
WHERE S.OBJECT LIKE ('ACC_WOFF_BILL_%')
AND S.OWNER = 'SZX') C
WHERE D.SID = C.SID;
----如果是 普通job 和应用确认后broken
SELECT 'exec sys.dbms_ijob.broken(' || JOB || ',true);'
FROM DBA_JOBS_RUNNING D,
(SELECT /*+RULE*/
SID
FROM V$ACCESS S
WHERE S.OBJECT LIKE ('ACC_WOFF_BILL_%')
AND S.OWNER = 'SZX') C
WHERE D.SID = C.SID
4. kill plsqldev连入的进程
SELECT 'kill -9 ' || SPID
FROM V$PROCESS
WHERE ADDR IN (SELECT /*+ RULE*/
PADDR
FROM V$SESSION
WHERE PROGRAM = 'plsqldev.exe'
AND OSUSER != '4A_xuzheng');
5. kill session 后,变化PADDR 的查询
注: status 为 NULL 的 不是后台进程的 一般都是标记为KILLED 的session
SELECT s.username,
s.status,
x.ADDR,
x.KSLLAPSC,
x.KSLLAPSN,
x.KSLLASPO,
x.KSLLID1R,
x.KSLLRTYP,
decode(bitand(x.ksuprflg, 2), 0, null, 1)
FROM x$ksupr x, v$session s
WHERE s.paddr(+) = x.addr and (s.status not in ('INACTIVE','ACTIVE') or s.status is null )
and bitand(ksspaflg, 1) != 0;
(六) 表,索引等分析
注:FORCE=>TRUE 如果统计锁定,此参数表示强制分析
1. 分析表
BEGIN
DBMS_STATS.GATHER_TABLE_STATS(OWNNAME => 'AISR',
TABNAME => 'SR_PROBLEM_WORK_ITEM',
-- PARTNAME=>'P200902',
-- GRANULARITY=>'PARTITION',
ESTIMATE_PERCENT => 1,
METHOD_OPT => 'FOR ALL COLUMNS SIZE 1',
NO_INVALIDATE => FALSE,
-- FORCE=>TRUE,
CASCADE => TRUE,
DEGREE => 10);
END;
/
2. 分析索引
BEGIN
DBMS_STATS.GATHER_INDEX_STATS(OWNNAME => 'AICBS',
INDNAME => 'IDX_AM_BILL_INV577_1205_201205',
-- PARTNAME=>'P200902',
-- GRANULARITY=>'PARTITION',
ESTIMATE_PERCENT => 1,
DEGREE => 10);
END;
/
3. 锁定表统计信息
exec DBMS_STATS.LOCK_TABLE_STATS('AICBS','I_UP_NOTIFY_576');
4. 手工设置统计信息
exec DBMS_STATS.SET_TABLE_STATS (ownname=>'MSPUSMP',tabname=>'T_MS_SEND_TASK',numrows=>600000,numblks=>1000,NO_INVALIDATE=>FALSE);
exec DBMS_STATS.SET_COLUMN_STATS (ownname=>'MSPUSMP',tabname=>'T_MS_SEND_TASK',colname=>'SCANID',distcnt=>600000,NO_INVALIDATE=>FALSE);
exec DBMS_STATS.SET_INDEX_STATS (ownname=>'MSPUSMP',indname=>'IDX_T_SEND_TASK_EXEC_SCHEDULE',numrows=>600000,numdist=>3,NO_INVALIDATE=>FALSE);
5. 判断分区表上是否存在全局索引
select owner, index_name
from dba_indexes
where table_name = 'AWARD_REWARD_TOTAL_FEE'
minus
select owner, index_name
from dba_part_indexes
where table_name = 'AWARD_REWARD_TOTAL_FEE'
and locality = 'LOCAL';
6. 表上索引的有效性检查(包含分区索引和非分区索引)
select index_owner, index_name, partition_name, status
from dba_ind_partitions a
where (a.index_owner, a.index_name) in
(select b.owner, b.index_name
from dba_indexes b
where table_name in
('i_all_user_sts_his', 'i_user_mcas_his', 'i_user_radius_his',
'i_user_mcas_index_his', 'cboss_busi_association')
and b.table_owner = 'cboss'
and b.partitioned = 'yes')
and status <> 'usable'
union all
select c.owner, c.index_name, 'no partition', status
from dba_indexes c
where table_name in
('i_all_user_sts_his', 'i_user_mcas_his', 'i_user_radius_his',
'i_user_mcas_index_his', 'cboss_busi_association')
and c.table_owner = 'cboss'
and c.partitioned = 'no'
and status = 'invalid';
(七) PGA和SGA
1. PGA使用率
--RAC各个节点PGA使用率
select a.inst_id,
round(b.value / 1024 / 1024, 1) pga_target,
round(a.pga_used_mb, 1),
round(a.pga_used_mb / (b.value / 1024 / 1024), 1) * 100 || '%' pga_used_pct
from (select inst_id, sum(PGA_ALLOC_MEM) / 1024 / 1024 pga_used_mb
from gv$process
group by inst_id) a,
gv$parameter b
where a.inst_id = b.inst_id
and b.name = 'pga_aggregate_target';
--单实例PGA使用率
select round(b.value / 1024 / 1024, 1) pga_target,
round(a.pga_used_mb, 1),
round(a.pga_used_mb / (b.value / 1024 / 1024), 1) * 100 || '%' pga_used_pct
from (select sum(PGA_ALLOC_MEM) / 1024 / 1024 pga_used_mb from v$process) a,
v$parameter b
where b.name = 'pga_aggregate_target';
2. 查历史的session的PGA使用情况
select a.time,a.inst_id,a.pgatotaluse,b.inst_id,b.pgatotaluse
from
(select b.snap_id,to_char(b.end_interval_time,'yyyy-mm-dd hh24:mi:ss') time,a.instance_number inst_id,round(a.value/1024/1024) pgatotaluse
from dba_hist_pgastat a,dba_hist_snapshot b
where a.snap_id=b.snap_id
and a.name='total PGA allocated'
and a.instance_number=1
and b.instance_number=1 ) a,
(select b.snap_id,to_char(b.end_interval_time,'yyyy-mm-dd hh24:mi:ss') time,a.instance_number inst_id,round(a.value/1024/1024) pgatotaluse
from dba_hist_pgastat a,dba_hist_snapshot b
where a.snap_id=b.snap_id
and a.name='total PGA allocated'
and a.instance_number=1
and b.instance_number=1) b
where a.snap_id=b.snap_id
order by 1;
3. session的PGA使用情况
select b.program,
b.status,
b.username,
b.MACHINE,b.osuser,
b.LOGON_TIME,
a.spid,
a.PGA_USED_MEM,
a.PGA_ALLOC_MEM,
a.PGA_FREEABLE_MEM,
a.PGA_MAX_MEM
from v$process a, v$session b
where a.addr = b.PADDR;
4. 共享池使用率
--RAC下查询多节点共享池使用率
select p.INST_ID,
a.POOL,
round(p.bytes / 1024 / 1024, 2) as size_mb,
round(a.bytes / 1024 / 1024, 2) as free_mb,
(1 - round( a.bytes / p.bytes ,4))*100||'%' as PCT_USED
from gv$sgainfo p, gv$sgastat a
where p.INST_ID = a.INST_ID(+)
and p.name = 'Shared Pool Size'
and a.name = 'free memory'
and a.pool = 'shared pool'
order by p.INST_ID asc;
--单实例共享池使用率
select a.POOL,
round(p.bytes / 1024 / 1024, 2) as size_mb,
round(a.bytes / 1024 / 1024, 2) as free_mb,
(1 - round( a.bytes / p.bytes ,4))*100||'%' as PCT_USED
from v$sgainfo p, v$sgastat a
where p.name = 'Shared Pool Size'
and a.name = 'free memory'
and a.pool = 'shared pool';
--共享池使用率(含子池)
SELECT 'shared pool (' ||
NVL(DECODE(TO_CHAR(ksmdsidx), '0', '0 - Unused', ksmdsidx), 'Total') || '):' subpool,
ROUND(SUM(ksmsslen) / 1048576, 2) TOTAL_MB,
ROUND(SUM(decode(ksmssnam, 'free memory', ksmsslen, '0')) / 1048576,2) FREE_MB,
100-ROUND(ROUND(SUM(decode(ksmssnam, 'free memory', ksmsslen, '0')) / 1048576,2) / ROUND(SUM(ksmsslen) / 1048576, 2),2) *100||'%' "USED%"
FROM x$ksmss
WHERE ksmsslen > 0
GROUP BY ROLLUP(ksmdsidx)
ORDER BY subpool ASC;
(八) 数据处理相关
1. dump方式导数据
----expdp
userid='/ as sysdba'
directory=dir_ljw
dumpfile=TAB.135.%U.dmp
schemas=AIJS
include=table:"in (select table_name from dba_tables where owner='AIJS' and table_name like 't%')"
CONTENT=DATA_ONLY /METADATA_ONLY/ALL
parallel=2
CLUSTER=N
--impdp
userid='/ as sysdba'
directory=dir_ljw
dumpfile=TAB.135.%U.dmp
--SCHEMAS =AIJS
REMAP_SCHEMA= SP: AIJS
transform=segment_attributes:n
TABLE_EXISTS_ACTION=replace
--network_link=gwcs1
CONTENT=DATA_ONLY /METADATA_ONLY/ALL
parallel=2
CLUSTER=N
2. sqlldr加载
--包含时间类型的
load data
infile "/arch/num.txt"
append into table icdmain.t_sce_usertype_main
fields terminated by "|"
(
ACCEPTPHONE ,
USERTYPE ,
USEDATE timestamp "yyyy-mm-dd hh24:mi:ss" ####时间类型
)
sqlldr \\'/ as sysdba \\' control=data.ctl log=0630.log bad=0630.txt discard=dis_0630.txt direct=y parallel=true
3. spool导出
sqlplus -s $user_name/$password@$service_name //-s 参数屏蔽打印到屏幕上的其他信息
set colsep ' '
set echo off
set trimout on
set trimspool on
set linesize 1000
set pagesize 0
set heading off
set termout off
set feedback off
spool 路径+生成文件名
select id || '|' || name from t_user; //执行的SQL,以”|”分隔
spool off
EOF
4. 批量插入或者更新
declare
row_num number := 0;
begin
for c_usr in (select /*+ parallel(a,8) */
*
from icdmip.t_sms_importutil) loop
insert into icdmip.t_mip_telelimit100501
(ina以上是关于oracle常用命令的主要内容,如果未能解决你的问题,请参考以下文章
ORA-01652 - 无法在表空间中将临时段扩展 4096 (oracle 10)
sql 如何解决Oracle“ORA-01652:无法在表空间X中用N扩展临时段”