You are on page 1of 34

alter system set dbwr_io_slaves=2 scope=spfile;

----datos en el sistema operativo


----------------------------------
while :
do
time
ps -fea|grep rman
sleep 5
echo " "
echo " "
echo " "
done
--redo log optimo
SELECT OPTIMAL_LOGFILE_SIZE FROM V$INSTANCE_RECOVERY
EXEC DBMS_STATS.lock_schema_stats('SCOTT');
EXEC DBMS_STATS.lock_table_stats('SCOTT', 'EMP');
EXEC DBMS_STATS.lock_partition_stats('SCOTT', 'EMP', 'EMP_PART1');
-----------------AWR----------------------------
-------------------------------------------------
select * from DBA_HIST_WR_CONTROL;
BEGIN
DBMS_WORKLOAD_REPOSITORY.modify_snapshot_settings(
retention => 43200, -- Minutes (= 30 Days). Current value retained if
NULL.
interval => 60); -- Minutes. Current value retained if NULL.
END;
/
Note. This example changes it to two weeks (14 days)
exec dbms_workload_repository.modify_snapshot_settings (retention => 14*24*60)
Note. This example changes it to 30 minutes
exec dbms_workload_repository.modify_snapshot_settings (interval => 30)
----------------------------------------------------------------------------
--ejecucuon de funcion
var result NUMBER;
EXEC :result := POR_FUN_SC_GET_GASTO_NOTARIO(1);
print result;
----------------------
----uptime EN DIAS
SELECT trunc(sysdate-startup_time) FROM sys.v_$instance;
select
'Hostname : ' || host_name
,'Instance Name : ' || instance_name
,'Started At : ' || to_char(startup_time,'DD-MON-YYYY HH24:MI:SS') stime
,'Uptime : ' || floor(sysdate - startup_time) || ' days(s) ' ||
trunc( 24*((sysdate-startup_time) -
trunc(sysdate-startup_time))) || ' hour(s) ' ||
mod(trunc(1440*((sysdate-startup_time) -
trunc(sysdate-startup_time))), 60) ||' minute(s) ' ||
mod(trunc(86400*((sysdate-startup_time) -
trunc(sysdate-startup_time))), 60) ||' seconds' uptime
from
sys.v_$instance;
---Sentencias Mas Pesadas por "Consumo de CPU"
SELECT sio.*
FROM
( SELECT cpu_time, first_load_time,last_load_time, elapsed_time,parsing_schema_
name,module, disk_reads, buffer_gets, rows_processed, executions,
round((buffer_gets - disk_reads) / (buffer_gets+1), 2)*100 as hit_ratio
, sql_text
from v$sql order by cpu_time desc) sio
WHERE ROWNUM < 10
and cpu_time/(executions+1) > 5000 and parsing_schema_name <> 'DBA_CON'
----Sentencias con Full Scans (no necesariamente malas)
select se.USERNAME,se.OSUSER,SE.MACHINE,SE.LOGON_TIME,se.module,se.sql_hash_valu
e, sq.sql_text as sql_text
from v$session se, v$sql sq
where se.sid in ( select sid
from v$session_wait
where event = 'db file scattered read'
and wait_time = 0)
and sq.hash_value = se.sql_hash_value;
select * from v$sqltext where HASH_VALUE=3987987197 ORDER BY PIECE
----saliuda en html
---------------------------------
SPOOL ASM_SECOND_corqa2.HTML
SET MARKUP HTML ON
SET ECHO ON
SET PAGESIZE 200
-----------------------------------
SELECT sql_text,executions,parsing_schema_name,au.module,first_load_time,last_lo
ad_time,last_active_time,username,status,osuser,machine,logon_time,wait_class,st
ate
FROM v$sqlarea vs , v$session au
WHERE (parsing_user_id != 0) AND
(au.USER#(+)=vs.parsing_user_id)
AND (executions >= 1)
and au.sql_hash_value = vs.hash_value
ORDER BY username,machine DESC
---------------------------------------
The following query can be used to find the total amount of memory allocated to
the PGA areas of all sessions:
SQL> select
sum(value)/1024/1024 Mb
from
v$sesstat s, v$statname n
where
n.STATISTIC# = s.STATISTIC# and
name = 'session pga memory';
hard parse
------------
select name,to_number(value)/1024/1024 bytes
from v$parameter where name ='shared_pool_size'
union all
select name,bytes/1024/1024
from v$sgastat where pool = 'shared pool' and name = 'free memory';
select to_char(100 * sess / calls, '999999999990.00') || '%' cursor_cache_hits,

to_char(100 * (calls - sess - hard) / calls, '999990.00') || '%' soft_parses,

to_char(100 * hard / calls, '999990.00') || '%' hard_parses
from ( select value calls from v$sysstat where name = 'parse count (total)' ),

( select value hard from v$sysstat where name = 'parse count (hard)' ),
( select value sess from v$sysstat where name = 'session cursor cache hits' ) ;


select'session_cached_cursors' parameter,lpad(value, 5) value,decode(value, 0,
' n/a', to_char(100 * used / value, '990') || '%') usage
from( select max(s.value) used from sys.v_$statname n, sys.v_$sessta
t s where n.name = 'session cursor cache count' and s.statistic# = n.sta
tistic#),
( select value from sys.v_$parameter where name = 'session_cached_cur
sors')union all select'open_cursors',lpad(value, 5),to_char(100 * used / value,
'990') || '%' from( select max(sum(s.value)) used from sys.v_$statname
n, sys.v_$sesstat s where n.name in ('opened cursors current', 'session
cursor cache count') and s.statistic# = n.statistic#
group by s.sid),( select value from sys.v_$parameter where name =
'open_cursors') ;
Si el valor del SESSION_CACHED_CURSORS se encuentra en el 100%, deberamos increm
entar el valor del parmetro con normalidad
--------------------------------
si se elimina un redo log
--------------------------------
select * from v$log;
sql> alter database clear logfile group 1;
sql> alter database clear unarchived logfile group 1;
alter database open;
----------------------------------------------------------------------
ERROR: ORA-03135: connection lost contact
sqlnet.ora
--------------
SQLNET.INBOUND_CONNECT_TIMEOUT=540
-------------------
select name,value from v$parameter where name IN ('db_name', 'db_domain');
select global_name from global_name;
alter database rename global_name to oralapd1;
UPDATE GLOBAL_NAME SET GLOBAL_NAME = 'ORALQA1';
commit;
commit;
-------------------------------------------------------------
Consulta Oracle SQL para conocer Espacio ocupado por usuario
SELECT owner, SUM(BYTES)/1024/1024 FROM DBA_EXTENTS MB
group by owner
---para saber si existe un campo en BLANCO
--------------------------------------------------
select * from cif_view_clientes where nvl(NOMBRE,'@') = '@';
sessiones inactivas ocupando memoria
------------------------------------------
select sum(PGA_ALLOC_MEM)/1024/1024
from v$process p, v$session s
where p.addr = s.paddr and s.status = 'INACTIVE';
SELECT SUM(VALUE)/1024/1024 || ' mb' "TOTAL MEMORY FOR ALL SESSIONS"
FROM V$SESSTAT, V$STATNAME
WHERE NAME = 'session uga memory'
AND V$SESSTAT.STATISTIC# = V$STATNAME.STATISTIC#;
SELECT SUM(VALUE)/1024/1024 || ' mb' "TOTAL MAX MEM FOR ALL SESSIONS"
FROM V$SESSTAT, V$STATNAME
WHERE NAME = 'session uga memory max'
AND V$SESSTAT.STATISTIC# = V$STATNAME.STATISTIC#;
Tables With No Indexes
-----------------------------
select OWNER, TABLE_NAME
from
(
select OWNER, TABLE_NAME
from dba_tables
minus
select TABLE_OWNER, TABLE_NAME
from dba_indexes
)
orasnap_noindex
where OWNER not in ('SYS','SYSTEM')
order by OWNER,TABLE_NAME
Tables With No PK
--------------------------
select OWNER,
TABLE_NAME
from dba_tables dt
where not exists (
select 'TRUE'
from dba_constraints dc
where dc.TABLE_NAME = dt.TABLE_NAME
and dc.CONSTRAINT_TYPE='P')
and OWNER not in ('SYS','SYSTEM')
order by OWNER, TABLE_NAME
cambibar nombre de bd
----------------------------
SQL> alter database rename global_name to COPY2.NETPOLAR.COM;

Database altered.

SQL> SELECT * FROM GLOBAL_NAME;
Monitorizacin de espacio de las tablas particionadas de la base de datos.
-------------------------------------------------------------
BREAK ON TABLA
SELECT NAME "TABLA",
COLUMN_NAME "COLUMNA DE PARTICIONAMIENTO",
COLUMN_POSITION "POSICION"
FROM DBA_PART_KEY_COLUMNS
WHERE OWNER IN ('USUARIO') AND
OBJECT_TYPE LIKE 'TABLE%'
ORDER BY 1,3;
SET LONG 10
BREAK ON TABLA SKIP 1
SELECT
SUBSTR(S.SEGMENT_NAME,1,25) "TABLA",
SUBSTR(S.PARTITION_NAME,1,13) "PARTICION",
P.HIGH_VALUE "MAXIMO",
SUBSTR(S.TABLESPACE_NAME,1,12) "TABLESPACE",
S.INITIAL_EXTENT/(1024) "INIT(Kb)",
S.NEXT_EXTENT/(1024) "NEXT(Kb)",
S.EXTENTS "NUM EXT",
S.MAX_EXTENTS "MAX EXT",
S.BYTES/(1024) "TAM(Kb)"
FROM DBA_SEGMENTS S,
DBA_TAB_PARTITIONS P
WHERE
S.OWNER IN ('USUARIO') AND
S.SEGMENT_NAME = P.TABLE_NAME AND
S.PARTITION_NAME = P.PARTITION_NAME AND
S.SEGMENT_TYPE LIKE 'TABLE%'
ORDER BY S.SEGMENT_NAME,
P.PARTITION_POSITION;
SET LONG 1000
CLEAR BREAKS
---------grant y default role
GRANT "R_PRV_CON" TO CDM_EXP;
ALTER USER CDM_EXP DEFAULT ROLE "ENDUSR", "R_BCT_CON", "R_CDM_ACT", "R_CIF_CON",
"R_PRV_CON";
version
------------
select substr(comp_name,1,40) nombre, substr(version,1,15) version, status from
dba_registry;
para debuggear
--------------------
GRANT SELECT_CATALOG_ROLE TO cif_exp;
GRANT DEBUG CONNECT SESSION TO cif_exp;
GRANT DEBUG ANY PROCEDURE TO cif_exp;
para formatear archivo grandes
-------------------------------
spool felix.txt
set termout off
set pagesize 0
set long 9000000
set linesize 150
col reg format a150 word_wrapped
---select () reg from dual;
spool off
DBCA(Database configuration assistant)
---deshabilitra modo archive
-------------------------------------------
shutdown immediate;
startup mount;
alter database noarchivelog;
alter system archive log stop;
-------------------------------------
eliminar datos duplicados
--------------------------
DELETE FROM tabla
WHERE ROWID NOT IN
(SELECT MIN(ROWID)
FROM tabla
GROUP BY columna1, columna2, columna3...);
SELECT COUNT(*) FROM joumdr E
WHERE E.ROWID > ANY (SELECT ROWID
FROM joumdr M
WHERE M.FEC_BUSSINESDATE = E.FEC_BUSSINESDATE
AND M.FEC_STAMP = E.FEC_STAMP
and m.NUM_IPCONEXION = e.NUM_IPCONEXION
and m.RUT_USUARIO = e.RUT_USUARIO
AND M.NUM_BRANCH = E.NUM_BRANCH
AND M.NUM_OPERATOR = E.NUM_OPERATOR
AND M.COD_SERIAL = E.COD_SERIAL)
AND TO_CHAR(FEC_STAMP,'yyyymm') = '201008' AND TRIM(COD_TRCO
DE) IN ('TDPE7000'))
AND TO_CHAR(FEC_STAMP,'yyyymm') = '201008' AND TRIM(COD_TRCODE) IN ('TDP
E7000');
------------------------------------
Estado de los segmentos de --------UNDO--------
-----------------------------------
SELECT SYSDATE AS fecha,
unexpired.unexpired,
expired.expired,
active.active
FROM (SELECT Sum(bytes / 1024 / 1024) AS unexpired
FROM dba_undo_extents
WHERE status = 'UNEXPIRED') unexpired,
(SELECT Sum(bytes / 1024 / 104) AS expired
FROM dba_undo_extents tr
WHERE status = 'EXPIRED') expired,
(SELECT CASE
WHEN Count(status) = 0
THEN 0
ELSE Sum(bytes / 1024 / 1024)
END AS active
FROM dba_undo_extents
WHERE status = 'ACTIVE') active;
Donde,
UNEXPIRED = significa que estos segmentos de UNDO no contienen ninguna transaccin
activa, pero estos contienen transacciones que todava son requeridos para FLASHB
ACK.
EXPIRED = significa que estos segmentos no son requeridos despus del periodo de
retencin definido en undo_retention.
ACTIVE = significa que estos segmentos de UNDO contienen transacciones activa
s, o sea, no se ha realizado commit.
--------------------------------------------------------------------------------
---------------------------------------
-------- transacciones estn ocupando segmentos de UNDO y/o generando bloqueos deb
ido a falta de commit o rollback
--------------------------------------------------------------------------------
---------------------------------------
SELECT v$transaction.status AS status_transaccion,
start_time,
logon_time,
blocking_session_status,
schemaname,
machine,
program,
module,
v$sqlarea.sql_text,
serial#,
sid,
username,
v$session.status AS status_sesion,
sql_id,
prev_sql_id
FROM v$transaction
INNER JOIN v$session
ON v$transaction.ses_addr = v$session.saddr
LEFT JOIN v$sqlarea
ON v$session.sql_id = v$sqlarea.sql_id;
------------------------------------------------------
SELECT begin_time,
end_time,
tuned_undoretention
FROM v$undostat
ORDER BY begin_time DESC
------------------------
undo retention optimo Y NO SOBREPASAR EL TAMAO EL TABLESPACE UNDO
-------------------------------------------------------------------------
SELECT d.undo_size / (1024 * 1024) "ACTUAL UNDO SIZE [MByte]",
Substr(e.VALUE,1,25) "ACTUAL UNDO RETENTION [Sec]",
Round((d.undo_size / (To_number(f.VALUE) * g.undo_block_per_sec))) "UNDO
RETENTION OPTIMO [Sec]"
FROM (SELECT Sum(a.bytes) undo_size
FROM v$datafile a,
v$tablespace b,
dba_tablespaces c
WHERE c.contents = 'UNDO'
AND c.status = 'ONLINE'
AND b.name = c.tablespace_name
AND a.ts# = b.ts#) d,
v$parameter e,
v$parameter f,
(SELECT Max(undoblks / ((end_time - begin_time) * 3600 * 24)) undo_block_
per_sec
FROM v$undostat) g
WHERE e.name = 'undo_retention'
AND f.name = 'db_block_size'
--PARA CAMBIAR UNDO RENTENTION
-------------------------------------
SQL > alter system set undo_retention=1831;
1.- Conectate como System o Sys y ejecuta:
select max(maxquerylen) from v$undostat;
2.- Verifica el valor del parmetro de UNDO_RETENTION
show parameter undo_retention
3.- Si el valor anterior es menor al resultado de la consulta, entonces modifica
el parmetro con el valor que recibiste de la consulta.
----------------------cuando se cambia la password de SYS en la base de datos OR
ACLE
--------------------------------------------------------------------------------
--------------
$ORACLE_HOME/dbs
orapwd file=$ORACLE_HOME/dbs/orapwCORQA1 password=mantencion entries=10 force=y
orapwd file=$ORACLE_HOME/dbs/orapwCORQAST password=mantencion entries=10 force=y
orapwd file=$ORACLE_HOME/dbs/orapwtest password=oracle entries=10 force=y
orapwd file=$ORACLE_HOME/dbs/orapworig password=oracle entries=10 force=y
remote_login_passwordfile = exclusive
select * from v$pwfile_users ;
grant sysdba to sys;
tablas externas
---------------------
CREATE TABLE CCENTER_EXT_OPER_CSV
(
ID_OPERACION VARCHAR2(50 BYTE),
COD_CLASE VARCHAR2(50 BYTE),
GLS_CLASE VARCHAR2(50 BYTE),
COD_SUBCLASE VARCHAR2(50 BYTE),
GLS_SUBCLASE VARCHAR2(50 BYTE),
NUM_CLIENTE VARCHAR2(50 BYTE)
)
ORGANIZATION EXTERNAL
( TYPE ORACLE_LOADER
DEFAULT DIRECTORY UTLFILEDIR
ACCESS PARAMETERS
( RECORDS DELIMITED BY NEWLINE
FIELDS TERMINATED BY ';' )
LOCATION (UTLFILEDIR:'OPERACIONES_MORA.CSV')
)
;
shared spool
-----------------------
select * from ( select POOL, NAME, BYTES, trunc(BYTES/1048576) as MBytes from v$
sgastat where pool='shared pool' order by BYTES desc ) where rownum <= 25;
select COMPONENT,current_size/1024/1024, min_size/1024/1024,max_size,user_specif
ied_size/1024/1024 from v$sga_dynamic_components
select * from v$db_cache_advice
select * from v$shared_pool_advice
select * from v$pga_target_advice
select * from v$sga_target_advice
alter system flush shared_pool;
alter system flush buffer_cache;
tamao minimo, promedio y alto de la shared spool y buffer cache
----------------------------------------------------------------------
select component, AVG(FINAL_SIZE)/1024/1024 "AVG FINAL", MEDIAN(FINAL_SIZE)/1024
/1024 "MEDIAN FINAL", MAX(FINAL_SIZE)/1024/1024 "MAX FINAL"
from v$sga_resize_ops
group by component;
select START_TIME, component, oper_type, oper_mode, initial_size/1024/1024 "INIT
IAL", FINAL_SIZE/1024/1024 "FINAL", END_TIME
from v$sga_resize_ops
where component in ('DEFAULT buffer cache', 'shared pool') and status = 'COMPLET
E'
order by start_time, component;
si da error de undo que no existe en el archivo de ALERTA-----CON SHUTDOWN ABORT
-------------------------------------------------------------
ORA-01092 ORACLE instance terminated. Disconnection forced
startup nomount;
alter system set UNDO_TABLESPACE='';
alter database mount;
alter database open;
-----------------------------------------------------------------
create undo tablespace UNDOTBS2 datafile 'RUT/undotbs2.dbf' size 200M autoextend
on maxsize 1024M;
alter system set UNDO_TABLESPACE='UNDOTBS2';
drop tablespace UNDOTBS1 including contents and datafiles;
shutdown immediate;
startup;
BLOQUE CORRUPTO
------------------
Select * from v$database_block_corruption;
select count(*) from V$DATABASE_BLOCK_CORRUPTION;
select count(*) from V$BACKUP_CORRUPTION;
select count(*) from V$COPY_CORRUPTION;
-------------------------------------------
eliminar los blocked corruptos ora-11578
-------------------------------------------
rman > blockrecover datafile 9 block 21;
RMAN> blockrecover corruption list ;
blockrecover datafile 30 block 2654797;
UNDO OPTIMO
--------------
SELECT Tamao Tablespace UNDO Actual AS "Parametro",
Sum(a.bytes) AS "Valor"
FROM v$datafile a,
v$tablespace b,
dba_tablespaces c
WHERE c.contents = UNDO
AND c.status = ONLINE
AND b.NAME = c.tablespace_name
AND a.ts# = b.ts#
UNION ALL
SELECT Bloques UNDO por segundo AS "Parametro",
Max(undoblks / ((end_time - begin_time) * 3600 * 24)) AS "Valor"
FROM v$undostat
UNION ALL
SELECT Tamao Bloque de Base De Datos AS "Parametro",
To_number(VALUE) AS "Valor"
FROM v$parameter
WHERE NAME = db_block_size
UNDO_RETENTION OPTIMO= TAMOS TABALESPACE ACTUAL EN BYTES
---------------------------------------
8192 * BLOQUES UNDO POR SEGUNDO
O BIEN,,OBTENER UNDO RETENTION OPTIMO CON ESTA QUERY
------------------------------------
SELECT d.undo_size / (1024 * 1024) "ACTUAL UNDO SIZE [MByte]",
Substr(e.VALUE,1,25) "ACTUAL UNDO RETENTION [Sec]",
Round((d.undo_size / (To_number(f.VALUE) * g.undo_block_per_sec))) "UNDO
RETENTION OPTIMO [Sec]"
FROM (SELECT Sum(a.bytes) undo_size
FROM v$datafile a,
v$tablespace b,
dba_tablespaces c
WHERE c.contents = 'UNDO'
AND c.status = 'ONLINE'
AND b.name = c.tablespace_name
AND a.ts# = b.ts#) d,
v$parameter e,
v$parameter f,
(SELECT Max(undoblks / ((end_time - begin_time) * 3600 * 24)) undo_block_
per_sec
FROM v$undostat) g
WHERE e.name = 'undo_retention'
AND f.name = 'db_block_size'
NOTA:
----
Para modificar el undo_retention de la base de datos y no superar en tamao los 1.
3 GB del Tablespace de UNDO
es necesario setear el undo_retention a 1831 segundos:
obtener PGA Correcto
-------------------------
SELECT ROUND(pga_target_for_estimate/1024/1024) target_mb,
estd_pga_cache_hit_percentage cache_hit_perc,
estd_overalloc_count
FROM V$PGA_TARGET_ADVICE;
select max (pga_used_mem) / 1024/1024 M from v$process;
select sum (pga_used_mem) / 1024/1024 from v $ process;
Shared pool advice v$shared_pool_advice
PGA target advice v$pga_target_advice
Data cache advice v$db_cache_advice
Java Pool advice v$java_pool_advice
--------bloque anonimo que elimina job
-----------------------------------------------
BEGIN
FOR each_job IN (SELECT job FROM dba_jobs where upper(what) like '%ACPKSS_JOBS
.PR_SUBMIT_JOBS%')
LOOP
BEGIN
dbms_job.remove(each_job.job);
dbms_output.put_line('Done: '||each_job.job);
EXCEPTION
WHEN OTHERS
THEN
dbms_output.put_line('Failed: '||each_job.job);
END;
COMMIT;
END LOOP;
END;
conexion de cliente con hora erronea
-----------------------------------------
srvctl getenv database -d core
srvctl setenv database -d core -t "TZ=SST3"
srvctl getenv database -d core
conexion de cliente con hora erronea----mARZO DE CADA AO
-----------------------------------------
srvctl getenv database -d core
srvctl setenv database -d core -t "TZ=SAT4"
srvctl getenv database -d core
From SQL*Plus as SYS get the last archived SCN using:
------------------------------------------------------
SELECT archivelog_change#-1 FROM v$database;
Para iniciar y bajar el servicio oracle rac con hp-ux, ejecutalo con
UNIX_STD=95 emctl start dbconsole
UNIX_STD=95 emctl stop dbconsole
UNIX_STD=95 emctl status dbconsole
-------------------------------------------
select 'alter system kill session '||''''|| sid|| ',' ||serial# || ''''|| ' imme
diate;'
from v$session where machine = 'srvpor3'
-------------------------------------------------------------------
-------- submitir job con sentencias delete
-------------------------------------------------------------------
-------------------------------------------------------------------
-- Creacin del JOB que realiza la limpieza en la base de datos.
SET SERVEROUTPUT ON
DECLARE
X NUMBER;
JobNumber varchar2(30);
begin
sys.dbms_job.submit(job => X,
what => 'delete from log_trans_movil t
where t.FEC_REQUEST_TIME < Add_months(sysdate, -1);
commit;
delete from sesion_movil t
where t.FEC_LOGIN < Add_months(sysdate, -1);
commit;',
next_date => TRUNC(SYSDATE + 1) +8/24,
interval => 'sysdate+(1/24)');
JobNumber := to_char(X);
dbms_output.put_line('numero job = ' ||JobNumber);
commit;

end;
/
-------------------------------------------------------------------
---hasta donde puedo bajar el RESIZE de los tablepace
select value from v$parameter where name = 'db_block_size'
select 'alter database datafile '''||file_name||''' resize ' ||
ceil( (nvl(hwm,1)*8192)/1024/1024 ) || 'm;' cmd
from dba_data_files a,
( select file_id, max(block_id+blocks-1) hwm
from dba_extents
group by file_id ) b
where a.file_id = b.file_id(+)
and ceil( blocks*8192/1024/1024) -
ceil( (nvl(hwm,1)*8192)/1024/1024 ) > 0
-----------------------------------------------
[MontoLiquidoCredito.getConsulta1] sql: begin ? := CIF_FUN_SC_GET_MTO_BRUTO_CRED
[MontoLiquidoCredito.getConsulta1] 1: 19
[MontoLiquidoCredito.getConsulta1] 2: 21/11/2011
[MontoLiquidoCredito.getConsulta1] 3: 21/10/2013
[MontoLiquidoCredito.getConsulta1] 4: 1000000
[MontoLiquidoCredito.getConsulta1] 5: 1
[MontoLiquidoCredito.getConsulta1] 6: 1
[MontoLiquidoCredito.getConsulta1] 7: 1
[MontoLiquidoCredito.getConsulta1] 8: 1
[MontoLiquidoCredito.getConsulta1] 9: 24
[MontoLiquidoCredito.getConsulta1] 10: 01/01/1960
var ret number;
exec :ret := CIF_FUN_SC_GET_MTO_BRUTO_CRED('19',to_date('21/11/2011','dd/mm/yyyy
'),to_date('21/10/2013','dd/mm/yyyy'),1000000,1,1,1,1,24,to_date('01/01/1960','d
d/mm/yyyy'));
print ret
var ret varchar2(100);
exec :ret:=POR_FUN_LIS_ULTIMOACCESO('0153126488','0153126488',5);
print ret
---------como ejecuytta funciones y procedimientos
var ret number;
exec :ret := Por_Fun_Lis_Actualiza_Op;
------------------------------------------------------------------
var crs refcursor;
var ret number;
exec :ret := por_fun_lis_saldofmutuos('0085249673',:crs);
print crs;
CREATE OR REPLACE PROCEDURE POR_ADMIN.Ppr_Sp_Lis_Consulta_Pagos(RutProveedor i
n VARCHAR2,
RutEmpPagadora i
n VARCHAR2,
FechaI i
n VARCHAR2,
FechaT i
n VARCHAR2,
Monto i
n VARCHAR2,
param i
n VARCHAR2,
Srv_Message o
ut VARCHAR2,
Srv_Status o
ut VARCHAR2,
cur o
ut Ppr_Decla.PCur1)
iS
var a varchar2(100)
var b varchar2(100)
var c refcursor
exec Ppr_Sp_Lis_Consulta_Pagos('0','0','01-01-2009','01-06-2009','50000','1',:a,
:b,:c)
------------------------------------------------------------
---sql en memoria--cache
SELECT SUBSTR(owner,1,10) Owner,
SUBSTR(type,1,12) Type,
SUBSTR(name,1,20) Name,
executions,
sharable_mem Mem_used,
SUBSTR(kept|| ,1,4) Kept?
FROM v$db_object_cache
WHERE type in (TRIGGER,'PROCEDURE,'PACKAGE BODY,'PACKAGE)
ORDER BY executions desc;
---OBJECTOS INVALIDOS
select OWNER,OBJECT_TYPE,COUNT(*)
from dba_objects
where STATUS='INVALID'
GROUP BY OWNER,OBJECT_TYPE
--------version del servidor de aplicaciones oracle
$iAS-home\config\ias.properties
-------enter en campos ---reemplazar
REPLACE(REPLACE(gls_comentario_cursatura,CHR(10),''),CHR(13),'')
--------TAMAO DE INDICE
SELECT segment_name,bytes/1024/1024
FROM DBA_SEGMENTS
WHERE segment_name IN (SELECT INDEX_NAME FROM DBA_INDEXES WHERE table_name='SOB
REGHIS')
----------------PARALLEL en forma paralela depende de la cantidad de cpu
---------------- NOLOGGING no graba informacion en los redo log
CREATE INDEX cust_dup_idx
ON customer(sex, hair_color, customer_id)
PARALLEL 4
NOLOGGING;
SQLLOAD scott/tiger CONTROL=con1.ctl DIRECT=TRUE PARALLEL=TRUE
------------obejos lock por 2 minutos o mas------------------------
--------------------------------------------------------------------
SELECT SUBSTR(TO_CHAR(w.session_id),1,5) WSID, p1.spid WPID,
SUBSTR(s1.username,1,12) "WAITING User",
SUBSTR(s1.osuser,1,8) "OS User",
SUBSTR(s1.program,1,20) "WAITING Program",
s1.client_info "WAITING Client",
SUBSTR(TO_CHAR(h.session_id),1,5) HSID, p2.spid HPID,
SUBSTR(s2.username,1,12) "HOLDING User",
SUBSTR(s2.osuser,1,8) "OS User",
SUBSTR(s2.program,1,20) "HOLDING Program",
s2.client_info "HOLDING Client",
o.object_name "HOLDING Object"
FROM gv$process p1, gv$process p2, gv$session s1,
gv$session s2, dba_locks w, dba_locks h, dba_objects o
WHERE w.last_convert > 120
AND h.mode_held != 'None'
AND h.mode_held != 'Null'
AND w.mode_requested != 'None'
AND s1.row_wait_obj# = o.object_id
AND w.lock_type(+) = h.lock_type
AND w.lock_id1(+) = h.lock_id1
AND w.lock_id2 (+) = h.lock_id2
AND w.session_id = s1.sid (+)
AND h.session_id = s2.sid (+)
AND s1.paddr = p1.addr (+)
AND s2.paddr = p2.addr (+)
ORDER BY w.last_convert desc;
------------------------------------------ object locked-----------
SELECT o.owner, o.object_name, o.object_type, o.last_ddl_time, o.status, l.sessi
on_id, l.oracle_username, l.locked_mode
FROM dba_objects o, gv$locked_object l
WHERE o.object_id = l.object_id;
---------------------------------------------
alter system flush shared_pool;
alter system flush buffer_cache;
para resetear parametros
--------------------------
alter system reset some_param scope=both sid='*';
---------------------------------------------
select * from database_properties;
alter database default tablespace users;
alter database default temporary tablespace tmp;
------------MOVER ARCHIVO O TABLESPACE
1.- poner offline tablespace
2.- copiar o mover archivo (mv)
3.- alter tablespace rename datafile 'orginen' to 'destino';
4.- poner online tablespace
o puede ser:
1.- montar la bd (mount)
2.-copiar archivo o mover (mv)
3.- alter database rename file 'origen' to 'destino';
4.- abrir db
-----sga automatica utilizada
SELECT component, current_size/1024/1024, min_size/1024/1024 FROM v$sga_dynamic_
components
---usuarios blocking--------
SELECT sid,serial#, username FROM v$session WHERE sid IN (SELECT BLOCKING_SESSIO
N FROM v$session);
------------------------------------------------------
alter system set db_file_multiblock_read_count=128;
----------GENERAR INFORMES CON EL AWR y ADDM---------------
@$ORACLE_HOME/rdbms/admin/awrrpt.sql
@$ORACLE_HOME/rdbms/admin/awrrpti.sql
@$ORACLE_HOME/rdbms/admin/addmrpt.sql
-------- library cache, si la division es mayor que 1 % se debe aumentar la shar
ed spool
SELECT
SUM(PINS) "EXECUTIONS",
SUM(RELOADS) "CACHE MISSES WHILE EXECUTING",
SUM(RELOADS)/SUM(PINS)*100
FROM
V$LIBRARYCACHE;
--------------ver el tamao utilizado de la shared pool
SELECT SUM (bytes)/1024/1024 FROM v$sgastat WHERE pool='shared pool' AND name NO
T IN ('free memory')
--------------ver el tamao total de la shared pool
SELECT SUM (bytes)/1024/1024 FROM v$sgastat WHERE pool='shared pool'
y la diferencia el memoria libre
--------generar trace con el error ORA-932
alter system set events='932 trace name errorstack level 3';
alter system set events='932 trace name errorstack off';
-------eliminar session
--------------------------
en windows
-------------
orakill <ORACLE_SID> <SPID>
ALTER SYSTEM enable restricted session;
ALTER SYSTEM checkpoint global;
spool kill_all.sql
SELECT 'execute kill_session('|| chr(39) || sid || chr(39) || ',' || chr(39) ||
serial# || chr(39) || ');'
FROM gv_$session
WHERE (username IS NOT NULL OR username <> 'SYS');
spool off
@kill_all
-------------------------------------------------------
SELECT sid,serial#,status FROM v$session WHERE paddr NOT IN (SELECT addr FROM v$
process)
SELECT s.sid, s.serial#, s.username,s.program,s.MODULE,s.osuser,s.paddr,p.addr,p
.program FROM v$session s, v$process p WHERE p.addr = s.paddr(+) order by 1 desc
SELECT s.sid, p.pid, s.program "Client", p.program "Server"
FROM v$session s full outer join v$process p
ON (p.addr = s.paddr)
ORDER BY p.pid
-----cursors
select 'session_cached_cursors' parameter, lpad(value, 5) value,
decode(value, 0, ' n/a', to_char(100 * used / value, '990') || '%') usage
from ( select max(s.value) used from V$STATNAME n, V$SESSTAT s
where n.name = 'session cursor cache count' and s.statistic# = n.statistic# ),
( select value from V$PARAMETER where name = 'session_cached_cursors' )
union all
select 'open_cursors', lpad(value, 5), to_char(100 * used / value, '990') || '%
'
from ( select max(sum(s.value)) used from V$STATNAME n, V$SESSTAT s
where n.name in ('opened cursors current', 'session cursor cache count') and s.s
tatistic# = n.statistic# group by s.sid ),
( select value from V$PARAMETER where name = 'open_cursors' );
------------ Identifying objects reloaded into the SHARED POOL again and again
select substr(owner,1,10) owner,substr(name,1,25) name, substr(type,1,15) type,
loads, sharable_mem
from v$db_object_cache
-- where owner not in ('SYS','SYSTEM') and
where loads > 1 and type in ('PACKAGE','PACKAGE BODY','FUNCTION','PROCEDURE')
order by loads DESC;
---------- Identify the SQL responsible for the most BUFFER HITS and/or DISK REA
DS. Si quiero ver que hay en el SQL AREA hago:
SELECT SUBSTR(sql_text,1,80) Text, disk_reads, buffer_gets, executions
FROM v$sqlarea
WHERE executions > 0
AND buffer_gets > 100000
AND DISK_READS > 100000
ORDER BY (DISK_READS * 100) + BUFFER_GETS DESC
/
--------- HIT RATIO BY SESSION:
SELECT SUBSTR(Username,1,15) username,
Consistent_Gets,
Block_Gets,
Physical_Reads,
100*(Consistent_Gets+Block_Gets-Physical_Reads)/
(Consistent_Gets+Block_Gets) HitRatio
FROM V$SESSION, V$SESS_IO
WHERE V$SESSION.SID = V$SESS_IO.SID
AND (Consistent_Gets+Block_Gets)>0
AND Username IS NOT NULL;
------ buffer busy waits---ver la vista v$session_wait y V$SESSION_EVENT
SELECT
p1 "File #",
p2 "Block #",
p3 "Reason Code"
FROM
v$session_wait
WHERE
event = 'buffer busy waits';
To identify the segment and segment type contended for, query DBA_EXTENTS using
the values for File Id and Block Id returned
from V$SESSION_WAIT (p1 and p2 columns):
SELECT segment_owner, segment_name
FROM DBA_EXTENTS
WHERE file_id = <&p1>
AND <&p2> BETWEEN block_id AND block_id + blocks - 1;
--------LOCK
SELECT a.SID Sesion_Bloquedora, b.SID Sesion_Bloqueada,
s.username, s.command, s.MODULE, s.terminal, s.program
FROM v$lock a, v$lock b, v$session s
WHERE a.SID != b.SID
AND a.ID1 = b.ID1
AND a.ID2 = b.ID2
AND b.request > 0
AND a.BLOCK = 1
AND s.sid=a.sid;


SELECT DISTINCT
a.sid "waiting sid"
, d.sql_text "waiting SQL"
, a.ROW_WAIT_OBJ# "locked object"
, a.BLOCKING_SESSION "blocking sid"
, c.sql_text "SQL from blocking session"
FROM v$session a, v$active_session_history b, v$sql c, v$sql d
WHERE a.event='enq: TX - row lock contention'
AND a.sql_id=d.sql_id
AND a.blocking_session=b.session_id
AND c.sql_id=b.sql_id
AND b.CURRENT_OBJ#=a.ROW_WAIT_OBJ#
AND b.CURRENT_FILE#= a.ROW_WAIT_FILE#
AND b.CURRENT_BLOCK#= a.ROW_WAIT_BLOCK#;
-------------
Finding the SQL Statement executed by Sessions Waiting for I/O
--------------
SELECT s.sql_address, s.sql_hash_value
FROM V$SESSION s, V$SESSION_WAIT w
WHERE w.event LIKE 'db file%read'
AND w.sid = s.sid ;
SELECT event, total_waits, time_waited, average_wait FROM v$system_event
WHERE event= 'enq: TX - row lock contention';
---------Finding Locks and Lock Holders
SELECT * FROM V$LOCK WHERE request>0:
---------To show only holders and waiters for locks being waited on, use the fol
lowing statement:
SELECT DECODE(request,0,'Holder: ','Waiter: ')||sid sess
, id1, id2, lmode, request, type
FROM V$LOCK
WHERE (id1, id2, type) IN
(SELECT id1, id2, type FROM V$LOCK WHERE request>0)
ORDER BY id1, request;
----los minutos de switch log-----------
SELECT TO_CHAR(first_time,'dd-mm-yyyy hh24:mi:ss') first_time,
ROUND(24 * 60 * (lead(first_time,1) over (ORDER BY first_time) -first
_time),2) minutes
FROM
v$log_history v
WHERE first_time > TO_DATE('01-08-2008','dd-mm-yyyy')
ORDER BY 1
-----cuenta swith log-----------------
SELECT TRUNC (first_time) "Date", COUNT (1) "Total",
SUM (DECODE (TO_CHAR (first_time, 'hh24'), '00', 1, 0)) "00",
SUM (DECODE (TO_CHAR (first_time, 'hh24'), '01', 1, 0)) "01",
SUM (DECODE (TO_CHAR (first_time, 'hh24'), '02', 1, 0)) "02",
SUM (DECODE (TO_CHAR (first_time, 'hh24'), '03', 1, 0)) "03",
SUM (DECODE (TO_CHAR (first_time, 'hh24'), '04', 1, 0)) "04",
SUM (DECODE (TO_CHAR (first_time, 'hh24'), '05', 1, 0)) "05",
SUM (DECODE (TO_CHAR (first_time, 'hh24'), '06', 1, 0)) "06",
SUM (DECODE (TO_CHAR (first_time, 'hh24'), '07', 1, 0)) "07",
SUM (DECODE (TO_CHAR (first_time, 'hh24'), '08', 1, 0)) "08",
SUM (DECODE (TO_CHAR (first_time, 'hh24'), '09', 1, 0)) "09",
SUM (DECODE (TO_CHAR (first_time, 'hh24'), '10', 1, 0)) "10",
SUM (DECODE (TO_CHAR (first_time, 'hh24'), '11', 1, 0)) "11",
SUM (DECODE (TO_CHAR (first_time, 'hh24'), '12', 1, 0)) "12",
SUM (DECODE (TO_CHAR (first_time, 'hh24'), '13', 1, 0)) "13",
SUM (DECODE (TO_CHAR (first_time, 'hh24'), '14', 1, 0)) "14",
SUM (DECODE (TO_CHAR (first_time, 'hh24'), '15', 1, 0)) "15",
SUM (DECODE (TO_CHAR (first_time, 'hh24'), '16', 1, 0)) "16",
SUM (DECODE (TO_CHAR (first_time, 'hh24'), '17', 1, 0)) "17",
SUM (DECODE (TO_CHAR (first_time, 'hh24'), '18', 1, 0)) "18",
SUM (DECODE (TO_CHAR (first_time, 'hh24'), '19', 1, 0)) "19",
SUM (DECODE (TO_CHAR (first_time, 'hh24'), '20', 1, 0)) "20",
SUM (DECODE (TO_CHAR (first_time, 'hh24'), '21', 1, 0)) "21",
SUM (DECODE (TO_CHAR (first_time, 'hh24'), '22', 1, 0)) "22",
SUM (DECODE (TO_CHAR (first_time, 'hh24'), '23', 1, 0)) "23"
FROM v$log_history
GROUP BY TRUNC (first_time), TO_CHAR (first_time, 'Dy')
ORDER BY 1;

break on report
compute avg maximum minimum of logs transactions Mbytes bpt on report
select trunc(completion_time) "Fecha",
count(*) "Logs",sum(next_change# - first_change# + 1) "Txs",
sum(blocks * block_size) / 1024000 "Mbytes",
sum(blocks * block_size) / sum(next_change# - first_change# + 1) "BPT"
from v$archived_log
where trunc(completion_time) < trunc(sysdate)
and trunc(completion_time) > (select min(completion_time)
from v$archived_log)
group by trunc(completion_time);
--------------------------------------------------------------------------
para saber el suaurio sys que permisos tiene
select * from v$pwfile_users;
grant sysdba to sys;
hit ratio de la base de datos
......................................
SELECT (P1.value + P2.value - P3.value) / (P1.value + P2.value)*100
FROM v$sysstat P1, v$sysstat P2, v$sysstat P3
WHERE P1.name = 'db block gets'
AND P2.name = 'consistent gets'
AND P3.name = 'physical reads';
mejorar el hit ratio
-----------------------
DECLARE
v_dummy dual.dummy%TYPE;
BEGIN
FOR I IN 1..10000000 LOOP
SELECT dummy INTO v_dummy FROM dual;
END LOOP;
END;
/

FOR I IN 1..10000000 LOOP
TIME
ps -fea|grep rman
END LOOP;
carga masiva de datos
----------------------------
create table test (a number);
BEGIN
FOR I IN 1..1000000 LOOP
insert into test values (13);
commit;
END LOOP;
end;
/
02:45
cAMBIO DE FECHA EN LA SESSION
-------------------------------
alter session set nls_language = 'SPANISH';
alter session set NLS_DATE_FORMAT='DDMMYYY';
-------------------------------------------------------------
cambiar nombre de la base de datos
-------------------------------------------------------------
SHUTDOWN IMMEDIATE
STARTUP MOUNT
% nid TARGET=SYS/sys_password@nombre_viejo_bd DBNAME=nombre_nuevo_bd SETNAME=YES
LOGFILE=nid.out
! nid TARGET=SYS/migracion@oralapd2 DBNAME=orapepe SETNAME=YES LOGFILE=nid.out
SHUTDOWN IMMEDIATE
STARTUP MOUNT
ALTER DATABASE OPEN RESETLOGS;
% nid TARGET=SYS/oracle REVERT=YES LOGFILE=$HOME/nid.log
saber si el oracle es de 32 o 64 bit
------------------------------------
cd $ORACLE_HOME/bin
file oracle
saber el character set
-----------------------
SELECT value$ character_set FROM PROPS$ WHERE name='NLS_CHARACTERSET';
Cantidad de CPU utilizada en un SP
------------------------------------
En 10g, Oracle agrega una nueva funcin,
DBMS_UTILITY.GET_CPU_TIME()
que sirve para saber la cantidad de CPU que es utilizada entre dos puntos de un
determinado proceso
DBMS_UTILITY.GET_TIME() diferencia de tiempos entre 2 puntos
---------------------------------------
Algunas consultas SQL muy tiles para el administrador de Oracle (estado de la bas
e de datos Oracle, parmetros generales, ficheros de control, conexiones actuales
a Oracle, nombre del ejecutable que se utiliza, nombre del usuario, diccionario
de datos (vistas y tablas)...
Vista que muestra el estado de la base de datos:
select * from v$instance
Consulta que muestra si la base de datos est abierta
select status from v$instance
Vista que muestra los parmetros generales de Oracle
select * from v$system_parameter
Versin de Oracle
select value from v$system_parameter where name = 'compatible'
Ubicacin y nombre del fichero spfile
select value from v$system_parameter where name = 'spfile'
Ubicacin y nmero de ficheros de control
select value from v$system_parameter where name = 'control_files'
Nombre de la base de datos
select value from v$system_parameter where name = 'db_name'
Vista que muestra las conexiones actuales a Oracle Para visualizarla es necesari
o entrar con privilegios de administrador
select osuser, username, machine, program
from v$session
order by osuser
Vista que muestra el nmero de conexiones actuales a Oracle agrupado por aplicacin
que realiza la conexin
select program Aplicacion, count(program) Numero_Sesiones
from v$session
group by program
order by Numero_Sesiones desc
Vista que muestra los usuarios de Oracle conectados y el nmero de sesiones por us
uario
select username Usuario_Oracle, count(username) Numero_Sesiones
from v$session
group by username
order by Numero_Sesiones desc
Propietarios de objetos y nmero de objetos por propietario
select owner, count(owner) Numero
from dba_objects
group by owner
order by Numero desc
Diccionario de datos (incluye todas las vistas y tablas de la Base de Datos)
select * from dictionary
select table_name from dictionary
Muestra los datos de una tabla especificada (en este caso todas las tablas que l
leven la cadena "EMPLO"
select * from ALL_ALL_TABLES where upper(table_name) like '%EMPLO%'
Tablas propiedad del usuario actual
select * from user_tables
Todos los objetos propiedad del usuario conectado a Oracle
select * from user_catalog
---------------
Consulta SQL para el DBA de Oracle que muestra los tablespaces, el espacio utili
zado, el espacio libre y los ficheros de datos de los mismos:
------------
Select t.tablespace_name "Tablespace", t.status "Estado",
ROUND(MAX(d.bytes)/1024/1024,2) "MB Tamao",
ROUND((MAX(d.bytes)/1024/1024) -
(SUM(decode(f.bytes, NULL,0, f.bytes))/1024/1024),2) "MB Usados",
ROUND(SUM(decode(f.bytes, NULL,0, f.bytes))/1024/1024,2) "MB Libres",
t.pct_increase "% incremento",
SUBSTR(d.file_name,1,80) "Fichero de datos"
FROM DBA_FREE_SPACE f, DBA_DATA_FILES d, DBA_TABLESPACES t
WHERE t.tablespace_name = d.tablespace_name AND
f.tablespace_name(+) = d.tablespace_name
AND f.file_id(+) = d.file_id GROUP BY t.tablespace_name,
d.file_name, t.pct_increase, t.status ORDER BY 1,3 DESC
---aumentar un datafile y temporal
alter database datafile 'ubicacion' resize 100m;
alter database tempfile 'ubicacion' resize 100m;
--agregar un nuevo datafile
alter tablespace TSPC_MDR_DAT_S add datafile 'ubicacion' size 50m;
---cambiar password de usuario
ALTER USER crd_exp IDENTIFIED BY crd_exp;
---------------------------------------------------------------------
Productos Oracle instalados y la versin:
select * from product_component_version
Roles y privilegios por roles:
select * from role_sys_privs
Reglas de integridad y columna a la que afectan:
select constraint_name, column_name from sys.all_cons_columns
Tablas de las que es propietario un usuario, en este caso "HR":
SELECT table_owner, table_name from sys.all_synonyms where table_owner like 'HR'
Otra forma ms efectiva (tablas de las que es propietario un usuario):
SELECT DISTINCT TABLE_NAME
FROM ALL_ALL_TABLES
WHERE OWNER LIKE 'HR'
Parmetros de Oracle, valor actual y su descripcin:
SELECT v.name, v.value value, decode(ISSYS_MODIFIABLE, 'DEFERRED',
'TRUE', 'FALSE') ISSYS_MODIFIABLE, decode(v.isDefault, 'TRUE', 'YES',
'FALSE', 'NO') "DEFAULT", DECODE(ISSES_MODIFIABLE, 'IMMEDIATE',
'YES','FALSE', 'NO', 'DEFERRED', 'NO', 'YES') SES_MODIFIABLE,
DECODE(ISSYS_MODIFIABLE, 'IMMEDIATE', 'YES', 'FALSE', 'NO',
'DEFERRED', 'YES','YES') SYS_MODIFIABLE , v.description
FROM V$PARAMETER v
WHERE name not like 'nls%' ORDER BY 1
Usuarios de Oracle y todos sus datos (fecha de creacin, estado, id, nombre, table
space temporal,...):
Select * FROM dba_users
Tablespaces y propietarios de los mismos:
select owner, decode(partition_name, null, segment_name,
segment_name || ':' || partition_name) name,
segment_type, tablespace_name,bytes,initial_extent,
next_extent, PCT_INCREASE, extents, max_extents
from dba_segments
Where 1=1 And extents > 1 order by 9 desc, 3
ltimas consultas SQL ejecutadas en Oracle y usuario que las ejecut:
select distinct vs.sql_text, vs.sharable_mem,
vs.persistent_mem, vs.runtime_mem, vs.sorts,
vs.executions, vs.parse_calls, vs.module,
vs.buffer_gets, vs.disk_reads, vs.version_count,
vs.users_opening, vs.loads,
to_char(to_date(vs.first_load_time,
'YYYY-MM-DD/HH24:MI:SS'),'MM/DD HH24:MI:SS') first_load_time,
rawtohex(vs.address) address, vs.hash_value hash_value ,
rows_processed , vs.command_type, vs.parsing_user_id ,
OPTIMIZER_MODE , au.USERNAME parseuser
from v$sqlarea vs , all_users au
where (parsing_user_id != 0) AND
(au.user_id(+)=vs.parsing_user_id)
and (executions >= 1) order by buffer_gets/executions desc
-----------------
select distinct vs.executions,vs.buffer_gets,to_char(to_date(vs.first_load_time
, 'YYYY-MM-DD/HH24:MI:SS'),'MM/DD HH24:MI:SS') first_load_time,
vs.sql_text, vs.module,vs.sharable_mem,
vs.persistent_mem, vs.runtime_mem, vs.sorts,
vs.parse_calls, vs.disk_reads, vs.version_count,
vs.users_opening, vs.loads,
rawtohex(vs.address) address, vs.hash_value hash_value ,
rows_processed , vs.command_type, vs.parsing_user_id ,
OPTIMIZER_MODE , au.USERNAME parseuser
from v$sqlarea vs , all_users au
where (parsing_user_id != 0) AND
(au.user_id(+)=vs.parsing_user_id)
and (executions >= 1) and vs.sql_text = 'select TO_NUMBER(NVL(NUM_ROL_EMPLEADO,0
)) into :b1 from CIF_VIEW_CLIENTES where TO_NUMBER(SUBSTR(NUM_IDEN,1,(LENGTH(
NUM_IDEN)-1)))=:b2'
order by buffer_gets/executions desc
Todos los ficheros de datos y su ubicacin:
select * from V$DATAFILE
Ficheros temporales:
select * from V$TEMPFILE
Tablespaces:
select * from V$TABLESPACE
Otras vistas muy interesantes:
select * from V$BACKUP
select * from V$ARCHIVE
select * from V$LOG
select * from V$LOGFILE
select * from V$LOGHIST
select * from V$ARCHIVED_LOG
select * from V$DATABASE
defragmentar la memoria oracle
--------------------------------
ALTER SYSTEM FLUSH SHARED_POOL;
ALTER SYSTEM FLUSH BUFFER_CACHE;
Memoria Share_Pool libre y usada
-----------------------------------
select name,to_number(value)/1024/1024 bytes
from v$parameter where name ='shared_pool_size'
union all
select name,bytes/1024/1024
from v$sgastat where pool = 'shared pool' and name = 'free memory';
---------------------------
Cursores abiertos por usuario
-------------------------------
SELECT MAX(a.value) AS highest_open_cur, p.value AS max_open_cur
FROM v$sesstat a, v$statname b, v$parameter p
WHERE a.statistic# = b.statistic#
AND b.name = 'opened cursors current'
AND p.name= 'open_cursors'
GROUP BY p.value;
select b.sid, a.username, b.value Cursores_Abiertos
from v$session a,
v$sesstat b,
v$statname c
where c.name in ('opened cursors current')
and b.statistic# = c.statistic#
and a.sid = b.sid
and a.username is not null
and b.value >0
order by 3
SELECT v.value as numopencursors ,s.machine ,s.osuser,s.username
FROM V$SESSTAT v, V$SESSION s
WHERE v.statistic# = 3 and v.sid = s.sid
SELECT sum(v.value)
FROM V$SESSTAT v, V$SESSION s
WHERE v.statistic# = 3 and v.sid = s.sid
select user_name, status, osuser, machine, a.sql_text, c.sql_text
from v$session b, v$open_cursor a, V$SQLAREA c
where a.sid = b.sid
and c.address = a.address
ALTER SYSTEM SET open_cursors=1005 SCOPE=BOTH;
---------------------------
Aciertos de la cach (no debe superar el 1 por ciento)
------------------------------------------------------------
select sum(pins) Ejecuciones, sum(reloads) Fallos_cache,
trunc(sum(reloads)/sum(pins)*100,2) Porcentaje_aciertos
from v$librarycache
where namespace in ('TABLE/PROCEDURE','SQL AREA','BODY','TRIGGER');
Sentencias SQL completas ejecutadas con un texto determinado en el SQL
-------------------------------------------------------------------------
SELECT c.sid, d.piece, c.serial#, c.username, d.sql_text
FROM v$session c, v$sqltext d
WHERE c.sql_hash_value = d.hash_value
and upper(d.sql_text) like '%WHERE CAMPO LIKE%'
ORDER BY c.sid, d.piece
--------------------------------------------------------------------------------
---
SELECT *
FROM v$sqlarea vs , v$session au
WHERE (parsing_user_id != 0) AND vs.sql_text LIKE '%SELECT "A9"."CLI_CNR_CLI%'
AND
(au.USER#(+)=vs.parsing_user_id)
AND (executions >= 1)
and au.sql_hash_value = vs.hash_value
--ORDER BY buffer_gets/executions DESC
ORDER BY first_load_time DESC
--------------------------------------------------------------------------------
---
Una sentencia SQL concreta (filtrado por sid)
SELECT c.sid, d.piece, c.serial#, c.username, d.sql_text
FROM v$session c, v$sqltext d
WHERE c.sql_hash_value = d.hash_value
and sid = 105
ORDER BY c.sid, d.piece
//Tamao ocupado por la base de datos (ES EL TAMAO USADO EN LA BASE DE DATOS)
select sum(BYTES)/1024/1024 MB from DBA_EXTENTS
//Tamao de los ficheros de datos de la base de datos (ES EL TAMAO TOTAL (ALOCATIAD
O))
select sum(bytes)/1024/1024 MB from dba_data_files
//Tamao ocupado por una tabla concreta sin incluir los ndices de la misma
select sum(bytes)/1024/1024 MB from user_segments
where segment_type='TABLE' and segment_name='NOMBRETABLA'
//Tamao ocupado por una tabla concreta incluyendo los ndices de la misma
select sum(bytes)/1024/1024 Table_Allocation_MB from user_segments
where segment_type in ('TABLE','INDEX') and
(segment_name='NOMBRETABLA' or segment_name in
(select index_name from user_indexes where table_name='NOMBRETABLA'))
//Tamao ocupado por una columna de una tabla
select sum(vsize('NOMBRECOLUMNA'))/1024/1024 MB from NOMBRETABLA
//Espacio ocupado por usuario
SELECT owner, SUM(BYTES)/1024/1024 FROM DBA_EXTENTS MB
group by owner
//Espacio ocupado por los diferentes segmentos (tablas, ndices, undo, rollback, c
luster, ...)
SELECT SEGMENT_TYPE, SUM(BYTES)/1024/1024 FROM DBA_EXTENTS MB
group by SEGMENT_TYPE
//Espacio ocupado por todos los objetos de la base de datos, muestra los objetos
que ms ocupan primero
SELECT SEGMENT_NAME, SUM(BYTES)/1024/1024 FROM DBA_EXTENTS MB
group by SEGMENT_NAME
order by 2 desc
//Obtener todas las funciones de Oracle: NVL, ABS, LTRIM, ...
SELECT distinct object_name
FROM all_arguments
WHERE package_name = 'STANDARD'
order by object_name
--
-- Listing of temp segments.
--
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;
--
-- Temp segment usage per session.
--
SELECT S.sid || ',' || S.serial# sid_serial, S.username, S.osuser, P.spid, S.m
odule,
P.program, SUM (T.blocks) * TBS.block_size / 1024 / 1024 mb_used, T.tab
lespace,
COUNT(*) statements
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,
P.program, TBS.block_size, T.tablespace
ORDER BY sid_serial;
--
-- Temp segment usage per statement.
--
SELECT S.sid || ',' || S.serial# sid_serial, S.username, Q.hash_value, Q.sql_te
xt,
T.blocks * TBS.block_size / 1024 / 1024 mb_used, T.tablespace
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;
---------------
habilitar trace ora-1652
-----------------
alter system set events '1652 trace name errorstack';
alter session set events '1652 trace name errorstack';
alter system set events '1001 trace name processstate 10';
alter system set events '1001 trace name context off';
desabilitar trace
--------------------
alter session set events '1652 trace name context off';
alter system set events '1652 trace name context off';
---------------------------------
espacio ocupado en rollback
-------------------------------------
SELECT s.username,
--s.sid,
--s.serial#,
t.used_ublk,
t.used_urec,
rs.segment_name,
r.rssize/1024/1024 as mbsize,
r.status,
sysdate
FROM v$transaction t,
v$session s,
v$rollstat r,
dba_rollback_segs rs
WHERE s.saddr = t.ses_addr
AND t.xidusn = r.usn
AND rs.segment_id = t.xidusn
ORDER BY t.used_ublk DESC;
---------------------------------
TABLESPACE TEMPORAL:
- Para ver los tablespaces temporales, megabytes y los bloques que tienen
SELECT tablespace_name,SUM(bytes)/1024/1024, SUM(blocks)
FROM dba_temp_files
GROUP BY tablespace_name
Para ver usuarios/consultas que estn usando temporal.
SELECT a.username,osuser,program,TABLESPACE, EXTENTS, blocks
FROM v$sort_usage a,
v$session b
WHERE a.SESSION_ADDR=b.saddr
Para ver ocupacin de espacio temporal por tablespace.
SELECT tablespace_name, used_extents,used_blocks , free_extents, free_blocks
FROM v$sort_segment
Cuando free_extents llega a 0 ---> ORA-01652
01652, 00000, "unable to extend temp segment by %s in tablespace %s"
// *Cause: Failed to allocate an extent for temp segment in tablespace.
// *Action: Use ALTER TABLESPACE ADD DATAFILE statement to add one or more
// files to the tablespace indicated.
Lo que te dicen aplicaciones de terceros como el TOAD no vale para NADA, te dice
que siempre est lleno.
No uso el enterprise manager pero supongo que tres cuartas de lo mismo.
TABLESPACE UNDO :
Para entender el tablespace de UNDO (modo automtico) hay que saber antes como fun
cionan los segmentos
de rollback. Sobre la forma circular en que se utilizan las extensiones lo podei
s leer en el link, revisar el manual del concepts tambin.
http://download-west.oracle.com/docs/cd/B10501_01/server.920/a96521/undo.htm - 8
888
De esta forma Oracle gestiona automticamente estos segmentos que se pueden ver to
dava en dba_rollback_segs
con nombres como estos _SYSSMU32$ , _SYSSMU33$ ....
el nico parmetro que se utiliza es undo_retention para indicar la cantidad de segu
ndos que se quiere
garantizar para mantener informacin de deshacer.
SELECT SID,USER,osuser,program, used_ublk
FROM v$transaction a,
v$session b
WHERE a.ses_addr=b.saddr
AND used_ublk > 0;
El campo used_ublk devuelve el nmero de bloques de undo usados (used undo blocks)
por sesin.
Otras vistas para monitorizar el undo como indica el enlace de arriba son:
V$UNDOSTAT
V$ROLLSTAT
V$TRANSACTION
DBA_UNDO_EXTENTS
---------------------------UNDO------------------------------
SELECT TO_CHAR(BEGIN_TIME, 'dd-mm-yyyy hh24:mi') begin_time, b.name TABLESPACE,
undoblks, txncount
FROM v$undostat a, v$tablespace b
WHERE a.undotsn=b.ts# ORDER BY begin_time DESC;
--------------------------
tamao de undo
----------------------------
SELECT
begin_time,
SUM (undoblks) OVER
(ORDER BY begin_time
RANGE BETWEEN (7 / 24) PRECEDING AND 0 FOLLOWING
) * 8 / 1024 undo_mb
FROM v$undostat
ORDER BY 1 DESC;
------------------
SELECT SUM(a.bytes) "UNDO_SIZE"
FROM v$datafile a,
v$tablespace b,
dba_tablespaces c
WHERE c.CONTENTS = 'UNDO'
AND c.status = 'ONLINE'
AND b.name = c.tablespace_name
AND a.ts# = b.ts#;

SELECT MAX(undoblks/((end_time-begin_time)*3600*24))
"UNDO_BLOCK_PER_SEC"
FROM v$undostat;
SELECT TO_NUMBER(value) "DB_BLOCK_SIZE [KByte]"
FROM v$parameter
WHERE name = 'db_block_size';
--------------------------------------------------------
---------------obteniedo undo optimo-------------------
SELECT d.undo_size/(1024*1024) "ACTUAL UNDO SIZE [MByte]",
SUBSTR(e.value,1,25) "UNDO RETENTION [Sec]",
ROUND((d.undo_size / (TO_NUMBER(f.value) *
g.undo_block_per_sec))) "OPTIMAL UNDO RETENTION [Sec]"
FROM (
SELECT SUM(a.bytes) undo_size
FROM v$datafile a,
v$tablespace b,
dba_tablespaces c
WHERE c.CONTENTS = 'UNDO'
AND c.status = 'ONLINE'
AND b.name = c.tablespace_name
AND a.ts# = b.ts#
) d,
v$parameter e,
v$parameter f,
(
SELECT MAX(undoblks/((end_time-begin_time)*3600*24))
undo_block_per_sec
FROM v$undostat
) g
WHERE e.name = 'undo_retention'
AND f.name = 'db_block_size'
/
----------------------------------
LOCKED
---------------------------------
SELECT oracle_username, owner, object_name, object_type, session_id, locked_mode

FROM v$locked_object v, DBA_OBJECTS d WHERE v.object_id = d.object_id
ORDER BY oracle_username,session_id
SELECT s.username,s.osuser,s.sid,s.Serial#,s.program,v.TYPE
FROM v$lock v, v$session s
WHERE v.SID=s.sid AND v.TYPE IN ('TM','TX')
ORDER BY s.sid,s.Serial#
ALTER SYSTEM KILL SESSION 'SID,SERIAL#';
SELECT b.username, b.serial#,
c.sid, c.owner
object_owner, c.object,
d.id1, a.sql_text SQL
FROM v$sqltext a,v$session b,
v$access c, v$lock d
WHERE a.address = b.sql_address
AND a.hash_value = b.sql_hash_value
AND b.sid = c.sid
AND b.lockwait = d.kaddr
AND c.owner NOT IN
('SYS','SYSTEM');
------------------------------------

select nvl(S.USERNAME,'Internal') username,
nvl(S.TERMINAL,'None') terminal,
L.SID||','||S.SERIAL# Kill,
U1.NAME||'.'||substr(T1.NAME,1,20) tab,
decode(L.LMODE,1,'No Lock',
2,'Row Share',
3,'Row Exclusive',
4,'Share',
5,'Share Row Exclusive',
6,'Exclusive',null) lmode,
decode(L.REQUEST,1,'No Lock',
2,'Row Share',
3,'Row Exclusive',
4,'Share',
5,'Share Row Exclusive',
6,'Exclusive',null) request
from V$LOCK L,
V$SESSION S,
SYS.USER$ U1,
SYS.OBJ$ T1
where L.SID = S.SID
and T1.OBJ# = decode(L.ID2,0,L.ID1,L.ID2)
and U1.USER# = T1.OWNER#
and S.TYPE != 'BACKGROUND'
order by 1,2,5
/