oracle常用命令

发布时间:2023-08-14 13:30


    设置一个事务的隔离级别
        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
      (inanitionid, instructionid, partid, acceptphone, note, operatetype)
      select icdmip.f_mip_getid,
             '1005130000000485',
             2806,
             c_usr.tel,
             '',
             '0'
        from dual;
    row_num := row_num + 1;
    if mod(row_num, 10000) = 0 then
      commit;
    end if;
  end loop;
  commit;
end;
/

(九)	常用命令
1.	常用DDL
2.	常用数据库命令
3.	常用主机命令

查看进程使用内存、CPU使用信息(内存含使用的共享内存)
hpux unix通用 
如按内存使用从大至小排序
UNIX95= ps -efo pid,vsz,pcpu,user,uid,args|sort +1 -rn|more

如按CPU使用从大至小排序
UNIX95= ps -efo pid,vsz,pcpu,user,uid,args|sort +2 -rn|more


查看具体进程信息:
UNIX95= ps -efo pid,vsz,pcpu,user,uid,args|grep 4247608

perf_testsdzw01/#UNIX95= ps -efo pid,vsz,pcpu,user,uid,args|grep 4247608
4247608 69504   0.2   oracle 211 oracleperf_testzw1 (LOCAL=NO) 
4833932   200   0.0     root   0 grep 4247608 
perf_testsdzw01/#
进程4247608使用内存大小为69504 KB

hpux查看前十内存消耗
ps -el | head -n 1 ;ps -el | grep -v SZ | sort +9 -r -n | head -n 10

aix查看前十内存消耗
ps aux | head -1 ; ps aux | sort -rn +3| head -n 10


7.	根据文件号和块号查找所属对象
a.
select *
  from dba_extents a
 where a.file_id = 1275
   and (788871 between a.block_id and a.block_id + a.blocks - 1);
b.
alter system dump datafile 1529   block  647096 ;




8.	查找隐含参数
col name format a20
col isdefault format a15
col ismod format a15
col isadj format a15
col value format a15
set linesize 150 pagesize 999
select
   x.ksppinm name,
   y.ksppstvl value,
   y.ksppstdf isdefault,
   decode(bitand(y.ksppstvf,7),1,'MODIFIED',4,'SYSTEM_MOD','FALSE') ismod,
   decode(bitand(y.ksppstvf,2),2,'TRUE','FALSE') isadj
 from
   sys.x$ksppi x,
   sys.x$ksppcv y
 where
   x.inst_id = userenv('Instance') and
   y.inst_id = userenv('Instance') and
   x.indx = y.indx and
   x.ksppinm like '%_&par%'
 order by
   translate(x.ksppinm, ' _', ' ')
/

9.	将TAF过来的连接切回去
select 'alter system disconnect session '''||sid||','||serial#||''' post_transaction;' 
from v$session 
where failed_over='YES';


10.	CRS(10g) 常用
crs主要进程
(1)crsd
负责管理ha操作
管理crs资源,如linstener,vip,ons,gsn等
由root用户管理、启动
(2)ocssd
管理各节点的关系,用于节点间通信
由oracle用户运行管理
(3)oprocd
集群进程管理 —Process monitor for the cluster. 
仅在没有使用vendor的集群软件状态下运行
(4)evmd
事件检测进程,由oracle用户运行管理

1.启CRS
起rac 之前必须先确认守护进程已经起来。
perf_testsdpb01/#ps -ef |grep d.bin
root用户:
# $CRS_HOME/bin/crsctl  enable   crs
# $CRS_HOME/bin/crsctl  stop   crs
# $CRS_HOME/bin/crsctl  start  crs     --起守护进程

2. 关闭crs资源,在任一节点oracle用户执行
perf_testsdec01:/home/oracle>crs_stop –all  
perf_testsdec02:/home/oracle>  crs_stat -t
Name           Type           Target    State     Host        
------------------------------------------------------------
ora.ebusi.db   application    OFFLINE   OFFLINE               
ora....i1.inst application    OFFLINE   OFFLINE               
ora....i2.inst application    OFFLINE   OFFLINE               
ora....01.lsnr application    OFFLINE   OFFLINE               
ora....c01.gsd application    OFFLINE   OFFLINE               
ora....c01.ons application    OFFLINE   OFFLINE               
ora....c01.vip application    OFFLINE   OFFLINE               
ora....02.lsnr application    OFFLINE   OFFLINE               
ora....c02.gsd application    OFFLINE   OFFLINE               
ora....c02.ons application    OFFLINE   OFFLINE               
ora....c02.vip application    OFFLINE   OFFLINE               
perf_testsdec02:/home/oracle> 
3.启动CRS资源
# crs_start -all 或者是srvctl start nodeapps -n hostname
srvctl status nodeapps -n hostname
srvctl start nodeapps -n hostname

srvctl start nodeapps -n perf_testrdwf01

srvctl stop nodeapps -n perf_testjdcr01
srvctl start nodeapps -n perf_testjdcr01
$ORA_CRS_HOME/bin/crs_stop –all只能停掉State为ONLINE的服务,状态为UNKNOWN的资源不能通过这个命令关闭,
因此可以通过$ORA_CRS_HOME/bin/crs_stop 服务名 的方式单独停止那些状态为UNKNOWN的资源。
4.启停crs资源(单个启停)
crs_stat |grep vip  --选择资源,比如 gsd ,然后使用crs_start 资源的具体名字。

perf_testjdkf01:/home/oracle> crs_stat |grep vip
NAME=ora.perf_testjdkf01.vip
NAME=ora.perf_testjdkf02.vip
perf_testjdkf01:/home/oracle> crs_stop ora.perf_testjdkf01.vip
11.	Patch验证冲突
如果是检查要打的补丁间是否有冲突,则执行类似命令:
$ opatch prereq CheckConflictAmongPatchesWithDetail -phBaseDir 
实际的命令可能是这样:
$ opatch prereq CheckConflictAmongPatchesWithDetail -phBaseDir $ORACLE_HOME/patches
如果要检查要打的补丁和已经打过的补丁的冲突,则执行下面的命令:
$ opatch prereq CheckConflictAgainstOHWithDetail -phBaseDir 
   su - oracle -c "opatch prereq CheckConflictAgainstOHWithDetail -ph ./15856537"

12.	序列告警检查
Select  ce.host_name as HOST_NAME,
       ce.instance_name as INSTNACE_NAME,
       sequence_owner as SEQUENCE_OWNER,
       sequence_name SEQUENCE_NAME,
       round((max_value - last_number) / (max_value - min_value), 2) * 100 as ROUND,
       min_value as MIN_VALUE,
       max_value as MAX_VALUE,
       last_number as LAST_NUMBER
  From dba_sequences sq, v$instance ce
 Where sequence_owner not in ('PRECISE1', 'PRECISE2', 'DSG', 'HP_DBSPI',
        'DBMON', 'DBSNMP', 'SYSMAN', 'SYS', 'SYSTEM')
   and cycle_flag = 'N'
   and round((max_value - last_number) / (max_value - min_value), 2) * 100 <= 20
   and ce.instance_number = 1;

(十)	SCN检查
 
查询数据库中数据量的变化情况:
select date1,daybyte, a.daybyte-lag(a.daybyte,1,a.daybyte) over(order by a.date1)
from 
(select to_char(snap_time,'yyyymmdd') date1,sum(used_gb) daybyte from tab_snap_tablespace_day where tablespace_name not like '%UNDO%' group by to_char(snap_time,'yyyymmdd')) a; 


查询数据库会话连接趋势:
select a.t,a.inst_id,a.currused,a.maxuserd,b.inst_id,b.currused,b.maxuserd
from 
(select a.snap_id,to_char(b.end_interval_time,'yyyy-mm-dd hh24:mi:ss') t,a.instance_number inst_id,a.current_utilization currused,a.max_utilization maxuserd 
from dba_hist_resource_limit a,dba_hist_snapshot b
where a.resource_name ='sessions' 
and a.snap_id=b.snap_id 
and a.instance_number=1
and b.instance_number=1) a,
(select a.snap_id,to_char(b.end_interval_time,'yyyy-mm-dd hh24:mi:ss') t,a.instance_number inst_id,a.current_utilization currused,a.max_utilization maxuserd
from dba_hist_resource_limit a,dba_hist_snapshot b
where a.resource_name ='sessions' 
and a.snap_id=b.snap_id 
and a.instance_number=2
and b.instance_number=2) b
where a.snap_id=b.snap_id
order by 1;

select inst_id,count(*) from gv$session group by inst_id order by 1;
select inst_id,count(*) from gv$session where status='ACTIVE' group by inst_id order by 1;





###########################################pdb##########################################


12c中,如何连接pluggable database:

使用默认的service连接pdb,创建pdb之后,在监听中自动添加以pdb为名的service;
用户在cluster中创建service,用户使用srvctl命令创建一个service并且关系到pdb上;
使用命令alter session set container=pdb;
使用Enterprise Manager Express。
 1. 使用默认service连接pdb:

  当创建pdb之后,使用lsnrctl status命令可以看到多了一个以pdb为名的service,如下的pdb01:

复制代码
[oracle@ora12c ~]$ lsnrctl status

LSNRCTL for Linux: Version 12.2.0.1.0 - Production on 12-MAY-2017 15:33:43

Copyright (c) 1991, 2016, Oracle.  All rights reserved.

Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=ora12c)(PORT=1521)))
STATUS of the LISTENER
------------------------
Alias                     LISTENER
Version                   TNSLSNR for Linux: Version 12.2.0.1.0 - Production
Start Date                12-MAY-2017 15:32:16
Uptime                    0 days 0 hr. 1 min. 26 sec
Trace Level               off
Security                  ON: Local OS Authentication
SNMP                      OFF
Listener Parameter File   /u01/app/oracle/product/12.2.0/db_1/network/admin/listener.ora
Listener Log File         /u01/app/oracle/diag/tnslsnr/ora12c/listener/alert/log.xml
Listening Endpoints Summary...
  (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=ora12c)(PORT=1521)))
  (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(KEY=EXTPROC1521)))
Services Summary...
Service "4d852a2714024610e0537838a8c07c53" has 1 instance(s).
  Instance "db12g", status READY, has 1 handler(s) for this service...
Service "db12g" has 1 instance(s).
  Instance "db12g", status READY, has 1 handler(s) for this service...
Service "db12gXDB" has 1 instance(s).
  Instance "db12g", status READY, has 1 handler(s) for this service...
Service "pdb01" has 1 instance(s).
  Instance "db12g", status READY, has 1 handler(s) for this service...
The command completed successfully
复制代码
  这里修改tnsname.ora这个文件,添加一个pdb的记录,就可以连接pdb:

复制代码
[oracle@ora12c admin]$ vi tnsnames.ora 
# tnsnames.ora Network Configuration File: /u01/app/oracle/product/12.2.0/db_1/network/admin/tnsnames.ora
# Generated by Oracle configuration tools.

LISTENER_DB12G =
  (ADDRESS = (PROTOCOL = TCP)(HOST = ora12c)(PORT = 1521))


DB12G =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = ora12c)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = db12g)
    )
  )

pdb01 =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = ora12c)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = pdb01)
    )
  )
复制代码
  使用该service进行连接:

复制代码
[oracle@ora12c admin]$ sqlplus scott/tiger@pdb01

SQL*Plus: Release 12.2.0.1.0 Production on Fri May 12 15:47:26 2017

Copyright (c) 1982, 2016, Oracle.  All rights reserved.


Connected to:
Oracle Database 12c Enterprise Edition Release 12.2.0.1.0 - 64bit Production

SQL> show con_name

CON_NAME
------------------------------
PDB01
复制代码
2. 使用srvctl命令在群集中添加服务连接pdb(这种方式应用于RAC环境):

  创建service,其中cdb名称为cpdb,pdb名称为pdb01,service为das,首选节点实例名称为cpdb1,次选节点实例名称为cpdb2:

[oracle@node1 bin]$ srvctl add service -d cpdb -s das -pdb pdb01 -preferred cpdb1 -available cpdb2
  查看创建的service:

[oracle@node1 bin]$ srvctl config service –d  -s 
  同样添加tnsname.ora记录:

复制代码
das =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = scan-ip)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = das)
    )
  )
复制代码
  启动service:

[oracle@nsnode1 bin]$ srvctl start service -d cpdb -service das
  测试连接:

复制代码
SQL> connect sys/oracle@das AS SYSDBA

Connected.

SQL> SHOW CON_ID;

CON_ID

3

SQL> SHOW CON_NAME;

CON_NAME

PDB01
复制代码
3. 使用命令进行切换:

复制代码
[oracle@node1 bin]$ sqlplus / as sysdba

SQL*Plus: Release 12.1.0.1.0 Production on Wed May 12 14:56:27 2017

Copyright (c) 1982, 2017, Oracle. All rights reserved. 

Connected to:

Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 - 64bit Production

With the Partitioning, Real Application Clusters, Automatic Storage Management, OLAP,

Advanced Analytics and Real Application Testing options
SQL> show con_name;

CON_NAME

CDB$ROOT

SQL> ALTER SESSION SET CONTAINER = PDB01;

Session altered.

SQL> SHOW CON_NAME;

CON_NAME

PDB01
复制代码
4.使用Enterprise Manager Express进行连接:

  在使用之前检查是否为EM配置了端口,需要为EM配置端口:

复制代码
SQL> select dbms_xdb_config.gethttpsport from dual;

GETHTTPSPORT
------------
           0

SQL> exec dbms_xdb_config.sethttpsport(5500);

PL/SQL procedure successfully completed.

SQL> select dbms_xdb_config.gethttpsport from dual;

GETHTTPSPORT
------------
        5500
复制代码
  切换到pdb,为pdb配置EM端口:

复制代码
SQL> alter session set container = pdb01;

Session altered.

SQL> select dbms_xdb_config.gethttpport from dual;

 GETHTTPPORT

       5051
复制代码
  然后使用EM和配置的端口连接pdb。


1、查看有多少pdb数据库:
SQL> show pdbs;
2、切换到指定容器数据库:
SQL> alter session set container=ORCLPDB;
3、启动容器数据库:
SQL> alter pluggable database ORCLPDB open;
4、关闭容器数据库:
SQL> alter pluggable database ORCLPDB close immediate;
5、查看数据库名字:
SQL> show con_name;
6、数据库的创建及删除:
--创建或克隆前要指定文件映射的位置(需要CBD下sysdba权限)
alter system set db_create_file_dest='/u01/app/oracle/oradata/orcl/orcl2';

--创建一个新的PDB:(需要CBD下sysdba权限)
create pluggable database test admin user admin identified by admin;

--不指定直接创建库;
create pluggable database salespdb admin user admin identified by admin file_name_convert=('/u01/app/oracle/oradata/orcl12c/pdbseed/','/u01/app/oracle/oradata/orcl12c/salespdb/');
--克隆PDB(需要CBD下sysdba权限)
create pluggable database orcl2 from orcl1; --test_pdb必须是打开的,才可以被打开

--删除PDB(需要CBD下sysdba权限)

alter pluggable database orcl2 close; --关闭之后才能删除
drop pluggable database orcl2 including datafiles; --删除PDB orcl2

--设置CDB启动PDB自动启动(在这里使用的是触发器)
CREATE OR REPLACE TRIGGER open_pdbs
AFTER STARTUP ON DATABASE
BEGIN
EXECUTE IMMEDIATE 'ALTER PLUGGABLE DATABASE ALL OPEN';
END open_pdbs;
7、PDB创建用户(链接到pdb数据库后创建用户):
create user hanfuyou identified by hanfuyou default tablespace users temporary tablespace temp;
grant connect,resource,unlimited tablespace to hanfuyou;

拔插与删除 PDB

1、拔出SALESPDB #必须连接到CDB$ROOT
#首先关闭SALESPDB
SQL> alter pluggable database SALESPDB close immediate;
SQL> alter pluggable database SALESPDB unplug into '/home/oracle/salespdb.xml';
#XML文件中包含了每个数据文件的位置,以及初始化参数等信息。
2、drop PDB
#关闭并且拔出PDB后才可以进行删除,删除时可以一起删除数据文件:
#同样需要连接到CDB$ROOT容器,执行下列语句:
SQL> drop pluggable database SALESPDB keep datafiles;
3、plug an unplugged PDB
#本机插入PDB
SQL> create pluggable database SALESPDB02 using '/home/oracle/salespdb.xml' nocopy tempfile reuse;
SQL> alter pluggable database SALESPDB02 open;

4、本机不同存放位置插入PDB
mkdir /u01/app/oracle/oradata/orcl12c/salespdb01/;

SQL> create pluggable database SALESPDB01 using '/home/oracle/salespdb.xml'
SOURCE_FILE_NAME_CONVERT=('/u01/app/oracle/oradata/orcl12c/salespdb/','/u01/app/salespdb/')
MOVE FILE_NAME_CONVERT=('/u01/app/salespdb/','/u01/app/oracle/oradata/orcl12c/salespdb01/')
PATH_PREFIX='/u01/app/oracle/oradata/orcl12c/salespdb01/' STORAGE (MAXSIZE 2G MAX_SHARED_TEMP_SIZE 100M);
这里xml文件中指示数据文件在/u01/app/oracle/oradata/orcl12c/salespdb/中,
而实际上数据文件在/u01/app/salespdb/中,
且最终我们要将数据文件放在/u01/app/oracle/oradata/orcl12c/salespdb01/中。





####
select a.sid,a.blocking_session,a.last_call_et,a.event,
object_name,
dbms_rowid.rowid_create(1,data_object_id,rfile#,ROW_WAIT_BLOCK#,ROW_WAIT_ROW#) "rowid" ,
c.sql_text,c.sql_fulltext
from v$session a,v$sqlarea c ,dba_objects,v$datafile
where a.blocking_session is not null
and a.sql_hash_value = c.hash_value 
and ROW_WAIT_OBJ#=object_id and file#=ROW_WAIT_FILE#;


select nvl(min(to_date(start_time,'mm/dd/yy hh24:mi:ss')),sysdate) as  trancDate from sys.v_$transaction




####################
AWRSRPT报告
@?/rdbms/admin/awrsqrpt.sql

生成单实例 AWR 报告
@$ORACLE_HOME/rdbms/admin/awrrpt.sql  ##常用
生成 Oracle RAC AWR 报告
@$ORACLE_HOME/rdbms/admin/awrgrpt.sql
生成指定数据库实例的 AWR 报告
@$ORACLE_HOME/rdbms/admin/awrrpti.sql ##常用
RAC下多实例AWR报告
@$ORACLE_HOME/rdbms/admin/awrrpti.sql
生成SQL语句的awr报告
@$ORACLE_HOME/rdbms/admin/awrsqrpi.sql
生成单实例 AWR 时段对比报告
@$ORACLE_HOME/rdbms/admin/awrddrpt.sql ##常用
生成 Oracle RAC AWR 时段对比报告
@$ORACLE_HOME/rdbms/admin/awrgdrpt.sql
生成特定数据库实例的 AWR 时段对比报告
@$ORACLE_HOME/rdbms/admin/awrddrpi.sql
Oracle RAC 环境下特定(多个)数据库实例的 AWR 时段对比报告
@$ORACLE_HOME/rdbms/admin/awrgdrpi.sql

ASH报告
@?/rdbms/admin/ashrpt.sql



#查看执行最慢的满SQL
select *
 from (select sa.SQL_TEXT,
        sa.SQL_FULLTEXT,
        sa.EXECUTIONS "执行次数",
        round(sa.ELAPSED_TIME / 1000000, 2) "总执行时间",
        round(sa.ELAPSED_TIME / 1000000 / sa.EXECUTIONS, 2) "平均执行时间",
        sa.COMMAND_TYPE,
        sa.PARSING_USER_ID "用户ID",
        u.username "用户名",
        sa.HASH_VALUE
     from v$sqlarea sa
     left join all_users u
      on sa.PARSING_USER_ID = u.user_id
     where sa.EXECUTIONS > 0
     order by (sa.ELAPSED_TIME / sa.EXECUTIONS) desc)
 where rownum <= 50;
 
 查看执行次数最多的SQL
 select *
 from (select s.SQL_TEXT,
        s.EXECUTIONS "执行次数",
        s.PARSING_USER_ID "用户名",
        rank() over(order by EXECUTIONS desc) EXEC_RANK
     from v$sql s
     left join all_users u
      on u.USER_ID = s.PARSING_USER_ID) t
 where exec_rank <= 100;
 
 
 
 --- 查询每天执行慢的SQL:
SELECT S.SQL_TEXT,
       S.SQL_FULLTEXT,
       S.SQL_ID,
       ROUND(ELAPSED_TIME / 1000000 / (CASE
               WHEN (EXECUTIONS = 0 OR NVL(EXECUTIONS, 1 ) = 1) THEN
                1
               ELSE
                EXECUTIONS
             END),
             2) "执行时间'S'",
       S.EXECUTIONS "执行次数",
       S.OPTIMIZER_COST "COST",
       S.SORTS,
       S.MODULE, --连接模式(JDBC THIN CLIENT:程序)
       -- S.LOCKED_TOTAL,
       S.PHYSICAL_READ_BYTES "物理读",
       -- S.PHYSICAL_READ_REQUESTS "物理读请求",
       S.PHYSICAL_WRITE_REQUESTS "物理写",
       -- S.PHYSICAL_WRITE_BYTES "物理写请求",
       S.ROWS_PROCESSED      "返回行数",
       S.DISK_READS          "磁盘读",
       S.DIRECT_WRITES       "直接路径写",
       S.PARSING_SCHEMA_NAME,
       S.LAST_ACTIVE_TIME
  FROM GV$SQLAREA S
 WHERE ROUND(ELAPSED_TIME / 1000000 / (CASE
               WHEN (EXECUTIONS = 0 OR NVL(EXECUTIONS, 1 ) = 1) THEN
                1
               ELSE
                EXECUTIONS
             END),
             2) > 5 --100 0000微秒=1S
   AND S.PARSING_SCHEMA_NAME = USER
   AND TO_CHAR(S.LAST_LOAD_TIME, 'YYYY-MM-DD') =
       TO_CHAR( SYSDATE, 'YYYY-MM-DD' )
   AND S.COMMAND_TYPE IN (2 , 3, 5, 6 , 189)
 ORDER BY "执行时间'S'" DESC;


/*  SQL中 COMMAND_TYPE意义: 
2:INSERT
3:SELECT
6:UPDATE
7:DELETE
189:MERGE
详情可通过查找V$SQLCOMMAND视图  */



#######################################
通过下面SQL脚本来检查某个时间段备份失败的记录:

SELECT * FROM V$RMAN_STATUS 
WHERE START_TIME >= TO_DATE(&START_TIME,'YYYY-MM-DD HH24:MI:SS')
  AND END_TIME   <= TO_DATE(&END_TIME  ,'YYYY-MM-DD HH24:MI:SS')
  AND OPERATION ='BACKUP'
  AND STATUS !='COMPLETED' 
  AND STATUS NOT LIKE 'RUNNING%'
  
查看备份成功的历史记录:

SELECT * FROM V$RMAN_STATUS 
WHERE START_TIME >= TO_DATE(&START_TIME,'YYYY-MM-DD HH24:MI:SS')
  AND END_TIME   <= TO_DATE(&END_TIME  ,'YYYY-MM-DD HH24:MI:SS')
  AND OPERATION ='BACKUP'
  AND STATUS ='COMPLETED'

从V$RMAN_BACKUP_JOB_DETAILS中查看RMAN备份更详细的信息。

SELECT START_TIME,
      END_TIME,
      OUTPUT_DEVICE_TYPE,
      STATUS,
      ELAPSED_SECONDS,
      COMPRESSION_RATIO,
      INPUT_BYTES_DISPLAY,
      OUTPUT_BYTES_DISPLAY
FROM V$RMAN_BACKUP_JOB_DETAILS
ORDER BY START_TIME DESC ;


查看所有备份集详细信息:

SELECT A.RECID "BACKUP SET",
       A.SET_STAMP,
        DECODE (B.INCREMENTAL_LEVEL,
                '', DECODE (BACKUP_TYPE, 'L', 'Archivelog', 'Full'),
                1, 'Incr-1级',
                0, 'Incr-0级',
                B.INCREMENTAL_LEVEL)
           "Type LV",
        B.CONTROLFILE_INCLUDED "包含CTL",
        DECODE (A.STATUS,
                'A', 'AVAILABLE',
                'D', 'DELETED',
                'X', 'EXPIRED',
                'ERROR')
           "STATUS",
        A.DEVICE_TYPE "Device Type",
        A.START_TIME "Start Time",
        A.COMPLETION_TIME "Completion Time",
        A.ELAPSED_SECONDS "Elapsed Seconds",
        A.BYTES/1024/1024/1024 "Size(G)",
        A.COMPRESSED,
        A.TAG "Tag",
        A.HANDLE "Path"
   FROM GV$BACKUP_PIECE A, GV$BACKUP_SET B
  WHERE A.SET_STAMP = B.SET_STAMP AND A.DELETED = 'NO'
RDER BY A.COMPLETION_TIME DESC;
 

查找某个备份集中包含数据文件

SELECT DISTINCT c.file#,A.SET_STAMP, D.NAME, C.CHECKPOINT_CHANGE#, C.CHECKPOINT_TIME
FROM V$BACKUP_DATAFILE C, V$BACKUP_PIECE A, V$DATAFILE D
WHERE A.SET_STAMP = C.SET_STAMP
    AND D.FILE# = C.FILE#
    AND A.DELETED='NO'
    AND c.set_stamp=&set_stamp
 ORDER BY C.FILE#;
 

查询某个备份集中控制文件

SELECT DISTINCT A.SET_STAMP,
                D.NAME,
                C.CHECKPOINT_CHANGE#,
                C.CHECKPOINT_TIME
 FROM V$BACKUP_DATAFILE C, V$BACKUP_PIECE A, V$CONTROLFILE D
 WHERE A.SET_STAMP = C.SET_STAMP
   AND C.FILE# = 0
   AND A.DELETED = 'NO'
   AND C.SET_STAMP = &SET_STAMP;
 

查看某个备份集中归档日志:

SELECT DISTINCT B.SET_STAMP,
                B.THREAD#,
                B.SEQUENCE#,
                B.FIRST_TIME,
                B.FIRST_CHANGE#,
                B.NEXT_TIME,
                B.NEXT_CHANGE#
 FROM V$BACKUP_REDOLOG B, V$BACKUP_PIECE A
 WHERE A.SET_STAMP = B.SET_STAMP
   AND A.DELETED = 'NO'
   AND B.SET_STAMP = &SET_STAMP
 ORDER BY THREAD#, SEQUENCE#;
 

查看某个备份集SPFILE

SELECT DISTINCT A.SET_STAMP, B.COMPLETION_TIME, HANDLE
FROM V$BACKUP_SPFILE B, V$BACKUP_PIECE A
 WHERE A.SET_STAMP = B.SET_STAMP
   AND A.DELETED = 'NO'
   AND B.SET_STAMP = &SET_STAMP;
 

查看RMAN的配置信息

SELECT NAME,VALUE FROM V$RMAN_CONFIGURATION;

查看备份信息
 SELECT A.RECID "BACKUP SET",
         A.SET_STAMP,
         B.CONTROLFILE_INCLUDED "包含CTL",
         DECODE (A.STATUS,
                 'A', 'AVAILABLE',
                 'D', 'DELETED',
                 'X', 'EXPIRED',
                 'ERROR')
            "STATUS",
         A.DEVICE_TYPE "Device Type",
         A.START_TIME "Start Time",
         A.COMPLETION_TIME "Completion Time",
         A.ELAPSED_SECONDS "Elapsed Seconds",
         A.TAG "Tag",
         A.HANDLE "Path"
    FROM GV$BACKUP_PIECE A, GV$BACKUP_SET B
   WHERE A.SET_STAMP = B.SET_STAMP AND A.DELETED = 'NO' and  a.set_count = b.set_count
ORDER BY A.COMPLETION_TIME  ;













1、mot环境导出数据:
sys用户登录数据库
SQL>create directory dp_xsgl as '/home/oracle';
expdp "'/ as sysdba'" tablespaces=xsgl dumpfile=xsgl.dmp logfile=exp.log directory=dp_xsgl  job_name=xsgl  //操作系统执行

2、将导出的文件传输到uat环境/home/oracle路径下,/home/oracle/xsgl.dmp

3、uat环境新建表空间及用户:
create tablespace xsgl3 datafile '/alidata/app/oracle/oradata/uatora02/xsgl_tbs3.dbf' size 1G  AUTOEXTEND ON NEXT 100M MAXSIZE 5G;
create user xsgl3 identified by xsgl3 default tablespace xsgl3;
grant connect,resource to xsgl3;

4、uat环境导入数据:
sys用户登录数据库
SQL>create directory dp_xsgl as '/home/oracle';
impdp "'/ as sysdba'" dumpfile=xsgl.dmp  logfile=imp.log directory=dp_xsgl remap_schema=xsgl:xsgl3 remap_tablespace=xsgl:xsgl3  //操作系统层面执行

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号