MERCADOS FINANCIEROS

martes, 1 de marzo de 2016

FLASHBACK TABLE EXAMPLE

sql> alter user hr account unlock;
sql> alter user hr identified by hr;
sql> connect hr/hr;
sql> create table prueba as (select * from employees);
sql> select count(*) from prueba;
sql> drop table prueba;
sql> select * from prueba;
sql> flashback table prueba to before drop;
sql> create table prueba as (select * from employees);
sql> drop table prueba;
sql> show recyclebin;
sql> purge recyclebin;


Borrado e Investigación de Recycle Bin

scott@LAB10G> DROP TABLE emp_flash;
Tabla borrada.
scott@LAB10G> SHOW RECYCLEBIN;
ORIGINAL NAME    RECYCLEBIN NAME                OBJECT TYPE
---------------- ------------------------------ ------------
DROP TIME
-------------------
EMP_FLASH        BIN$sOdkxF+YR8C+UxoQnqCdPQ==$0 TABLE
2007-08-30:15:59:29
scott@LAB10G> SELECT object_name, original_name, type FROM recyclebin;
OBJECT_NAME                    ORIGINAL_NAME   TYPE
------------------------------ --------------- ----------
BIN$w0Kbu7YCT+itQjl0RD9PCQ==$0 EMP_FLASH_TRG   TRIGGER
BIN$sOdkxF+YR8C+UxoQnqCdPQ==$0 EMP_FLASH       TABLE
BIN$yfqwjE40Q+ueUv019AJaSA==$0 EMP_FLASH_PK    INDEX
Observamos que cuando ejecuto el comando SHOW RECYCLEBIN solo veo el objeto “padre” y no los objetos asociados. Para ver todos los objetos borrados debo consultar la vista RECYCLEBIN.

Recupero con Flashback DROP

scott@LAB10G> FLASHBACK TABLE emp_flash TO BEFORE DROP;
Flashback terminado.
scott@LAB10G> SHOW RECYCLEBIN;
scott@LAB10G> SELECT object_name, original_name, type FROM recyclebin;
ninguna fila seleccionada
scott@LAB10G> SELECT count(1) FROM emp_flash;
  COUNT(1)
----------
        6
scott@LAB10G> SELECT object_name, object_type
 2  FROM user_objects WHERE object_name like 'EMP_FLASH%';
OBJECT_NAME                    TYPE
------------------------------ ----------
EMP_FLASH                      TABLE
scott@LAB10G> SELECT index_name, index_type
 2*  FROM user_indexes WHERE table_name = 'EMP_FLASH';
INDEX_NAME                     INDEX_TYPE
------------------------------ ---------------------------
BIN$yfqwjE40Q+ueUv019AJaSA==$0 NORMAL
scott@LAB10G> SELECT name, type
 2*  FROM user_dependencies WHERE referenced_name = 'EMP_FLASH';
NAME                           TYPE
------------------------------ ----------
BIN$w0Kbu7YCT+itQjl0RD9PCQ==$0 TRIGGER
scott@LAB10G> ALTER INDEX "BIN$yfqwjE40Q+ueUv019AJaSA==$0" RENAME TO emp_flash_pk;
Indice modificado.
scott@LAB10G> ALTER TRIGGER "BIN$w0Kbu7YCT+itQjl0RD9PCQ==$0" RENAME TO emp_flash_trg;
Disparador modificado.
scott@LAB10G> ALTER TRIGGER emp_flash_trg COMPILE;
Disparador modificado.
scott@LAB10G> SELECT object_name, object_type
  2  FROM user_objects WHERE object_name like 'EMP_FLASH%';
OBJECT_NAME                    TYPE
------------------------------ ----------
EMP_FLASH                      TABLE
EMP_FLASH_PK                   INDEX
EMP_FLASH_TRG                  TRIGGER
Cuando una tabla es recuperada desde el Recycle Bin, se restaura la tabla y se renombra automáticamente con su nombre original.
Los objetos asociados como los índices, constraints o triggers también son restaurados, pero sus nombres originales no se recuperan, lo que significa que siguen siendo de la forma BIN$.
Una vez que finalizamos la operación de FLASHBACK no hay manera de averiguar los nombres originales de estos objetos. Por lo tanto siempre es buena idea consultarlos antes de realizar el recupero, entonces luego del FLASHBACK DROP de la tabla podemos hacer un RENAME de los objetos asociados a su nombre original.

Más de una versión en Recycle Bin

scott@LAB10G> DROP TABLE emp_flash;
Tabla borrada.
scott@LAB10G> CREATE TABLE emp_flash AS (select * from emp where empno > 7700);
Tabla creada.
scott@LAB10G> DROP TABLE emp_flash;
Tabla borrada.
scott@LAB10G> SHOW RECYCLEBIN;
ORIGINAL NAME    RECYCLEBIN NAME                OBJECT TYPE
---------------- ------------------------------ ------------
DROP TIME
-------------------
EMP_FLASH        BIN$4PK0jfk4R1uFiZLIQ7HHIg==$0 TABLE
2007-08-30:16:55:41
EMP_FLASH        BIN$C+EJy7/qThipip4yLQM8fQ==$0 TABLE
2007-08-30:16:54:59
scott@LAB10G> SELECT object_name, original_name, type, droptime, base_object FROM RECYCLEBIN;
OBJECT_NAME                    ORIGINAL_NAME   TYPE
------------------------------ --------------- ----------
DROPTIME            BASE_OBJECT
------------------- -----------
BIN$4PK0jfk4R1uFiZLIQ7HHIg==$0 EMP_FLASH       TABLE
2007-08-30:16:55:41       53938
BIN$PyLtYlEpTPOUVUDbW/vTrQ==$0 EMP_FLASH_PK    INDEX
2007-08-30:16:54:59       53934
BIN$DTlnXxLtQ0u5d4XPW9auZQ==$0 EMP_FLASH_TRG   TRIGGER
2007-08-30:16:54:59       53934
BIN$C+EJy7/qThipip4yLQM8fQ==$0 EMP_FLASH       TABLE
2007-08-30:16:54:59       53934
scott@LAB10G> FLASHBACK TABLE "BIN$C+EJy7/qThipip4yLQM8fQ==$0" TO BEFORE DROP RENAME TO emp_flash_v1;
Flashback terminado.
scott@LAB10G> FLASHBACK TABLE "BIN$4PK0jfk4R1uFiZLIQ7HHIg==$0" TO BEFORE DROP RENAME TO emp_flash_v2;
Flashback terminado.

miércoles, 24 de febrero de 2016

RMAN VALIDATE BACKUPSET

RMAN> VALIDATE BACKUPSET  14;
Starting validate at 24-FEB-16
allocated channel: ORA_DISK_1
channel ORA_DISK_1: SID=45 device type=DISK
channel ORA_DISK_1: starting validation of datafile backup set
channel ORA_DISK_1: reading from backup piece /u02/backups/rman/orcl/2016-02-24/incremental0_ORCL_0gquoou2_1_1_20160224.bak
channel ORA_DISK_1: piece handle=/u02/backups/rman/orcl/2016-02-24/incremental0_ORCL_0gquoou2_1_1_20160224.bak tag=BACKUP INCR LEVEL 0 FS
channel ORA_DISK_1: restored backup piece 1
channel ORA_DISK_1: validation complete, elapsed time: 00:00:02
Finished validate at 24-FEB-16
RMAN>

SQL modificar /c

SQL> select * from v$instanze;
select * from v$instanze
              *
ERROR at line 1:
ORA-00942: table or view does not exist
SQL> c/z/c
  1* select * from v$instance
SQL> /

lunes, 22 de febrero de 2016

Técnicas para extraer nuestros backups del ASM

Técnicas para extraer nuestros backups del ASM

  • Opción 1: Desde la versión de manejador de base de datos 11g Release1 tenemos disponible el comando cp perteneciente al utilitario asmcmd. Esta opción fue presentada y desarrollada en el articulo: "Protegiendo backups de RMAN contra fallos de la SAN (Parte I)"
  • Opción 2: Desde versiones anteriores al manejador de base de datos 11g, tenemos las opciones de: Backup Backupset perteneciente al conjunto de comandos y opciones de RMAN. Esta opción fue presentada y desarrollada en el articulo: "Protegiendo backups de RMAN contra fallos de la SAN (Parte II)"
  • Opción 3: Desde la versión de base de datos 10g tenemos la existencia del paquete DBMS_TRANSFER. Esta será la técnica utilizada para el presente artículo.
A continuación trabajaremos con la opción nro.3:

DBMS_FILE_TRANSFER

The DBMS_FILE_TRANSFER package provides procedures to copy a binary file within a database or to transfer a binary file between databases.
Oracle® Database PL/SQL Packages and Types Reference
11g Release 2 (11.2)
http://docs.oracle.com/cd/E11882_01/appdev.112/e25788/d_ftran.htm

Vamos a realizarlo:
Base de Datos: DB
Diskgroup (DATA): +DATA
Diskgroup (FRA): +FRA
Paso1: Tomar backup full con RMAN estableciendo una etiqueta que nos pueda ayudar a identificar unívocamente las piezas pertenecientes a este:
rman_backup_full.sh
export ORACLE_SID=MYDB
export V_DATE=`date +%d%m%Y_%H%M`
export V_LOGFILE=/BKFULL_MYDB_RMAN_$V_DATE.log
rman target / @/run.rcv log=$V_LOGFILE

run.rcv
run {
       backup database tag='FULL_WEEKLY';
}
exit

En el caso presente estamos tomando un backup full de la BBDD y el elemento que nos ayudara a identificar de forma univoca el mismo será el TAG aplicado en la sentencia de backup full.
Una vez tomado el backup, visualizamos la piezas generadas del mismo:
RMAN> List Backup;
using target database control file instead of recovery catalog
List of Backup Sets
===================


BS Key  Type LV Size       Device Type Elapsed Time Completion Time
------- ---- -- ---------- ----------- ------------ ---------------
5       Full    1019.86M   DISK        00:01:15     10-NOV-11
        BP Key: 5   Status: AVAILABLE  Compressed: NO  Tag: FULL_WEEKLY
        Piece Name: +FRA/mydb/backupset/2011_11_10/nnndf0_full_weekly_0.271.766859353
  List of Datafiles in backup set 5
  File LV Type Ckp SCN    Ckp Time  Name
  ---- -- ---- ---------- --------- ----
  1       Full 1072131    09-NOV-11 +DATA/mydb/datafile/system.256.766584645
  2       Full 1072131    09-NOV-11 +DATA/mydb/datafile/sysaux.257.766584645
  3       Full 1072131    09-NOV-11 +DATA/mydb/datafile/undotbs1.258.766584647
  4       Full 1072131    09-NOV-11 +DATA/mydb/datafile/users.259.766584647
  5       Full 1072131    09-NOV-11 +DATA/mydb/datafile/example.276.766585261

BS Key  Type LV Size       Device Type Elapsed Time Completion Time
------- ---- -- ---------- ----------- ------------ ---------------
6       Full    9.58M      DISK        00:00:01     10-NOV-11
        BP Key: 6   Status: AVAILABLE  Compressed: NO  Tag: FULL_WEEKLY
        Piece Name: +FRA/mydb/backupset/2011_11_10/ncsnf0_full_weekly_0.269.766859431
  SPFILE Included: Modification time: 09-NOV-11
  SPFILE db_unique_name: mydb
  Control File Included: Ckp SCN: 1072131      Ckp time: 09-NOV-11
RMAN>
En el log presentado se puede apreciar la generación de 2 piezas 
+FRA/mydb/backupset/2011_11_10/nnndf0_full_weekly_0.271.766859353 & 
+FRA/mydb/backupset/2011_11_10/ncsnf0_full_weekly_0.269.766859431).  

Cada pieza posee atributos únicos, en esta ocasión determinaremos las mismas a transferir mediante los atributos TAG & BS KEY. Ambas piezas representan el objetivo para transferir a una localización de disco diversa al FRA.
Paso2: Visualizando localizaciones de piezas generadas en el FRA
Visualicemos las especificaciones de las piezas generadas a través de las vistas de diccionario de datos de nuestra base de datos.
SQL> select HANDLE from v$backup_piece
  2  where TAG='FULL_WEEKLY';

HANDLE
-----------------------------------------------------------------
+FRA/mydb/backupset/2011_11_10/nnndf0_full_weekly_0.271.766859353
+FRA/mydb/backupset/2011_11_10/ncsnf0_full_weekly_0.269.766859431
SQL>

Paso3: Creación del paquete DBMS_FILE_TRANSFER.
Una vez divisadas las piezas a transferir externamente de nuestro almacenamiento ASM. Procederemos a verificar si el paquete DBMS_FILE_TRANSFER esta creado.
SQL> desc dbms_file_transfer
PROCEDURE COPY_FILE
Argument Name                  Type               In/Out Default?
------------------------------ ------------------ ------ --------
SOURCE_DIRECTORY_OBJECT        VARCHAR2                IN
SOURCE_FILE_NAME               VARCHAR2                IN
DESTINATION_DIRECTORY_OBJECT   VARCHAR2                IN
DESTINATION_FILE_NAME          VARCHAR2                IN
PROCEDURE GET_FILE
Argument Name                  Type               In/Out Default?
------------------------------ ------------------ ------ --------
SOURCE_DIRECTORY_OBJECT        VARCHAR2                IN
SOURCE_FILE_NAME               VARCHAR2                IN
SOURCE_DATABASE                VARCHAR2                IN
DESTINATION_DIRECTORY_OBJECT   VARCHAR2                IN
DESTINATION_FILE_NAME          VARCHAR2                IN
PROCEDURE PUT_FILE
Argument Name                  Type               In/Out Default?
------------------------------ ------------------ ------ --------
SOURCE_DIRECTORY_OBJECT        VARCHAR2                IN
SOURCE_FILE_NAME               VARCHAR2                IN
DESTINATION_DIRECTORY_OBJECT   VARCHAR2                IN
DESTINATION_FILE_NAME          VARCHAR2                IN
DESTINATION_DATABASE           VARCHAR2                IN

SQL>

Si el mismo no esta creado, podremos crearlo con el siguiente script:
{ORACLE_HOME}/rdbms/admin/dbmsxfr.sql
Si algún usuario diferente de sys necesita acceso al mismo, podemos otorgar el privilegio de la siguiente manera:
GRANT EXECUTE ON dbms_file_transfer TO DBO;
Paso4: Creación de directorios origen y destino para la transferencia
SQL> create directory source_dir as
 2  '+FRA/mydb/backupset/2011_11_10';

Directory created.

SQL> create directory target_dir as
 2  '/home/oracle/MyExternalFileSystem';

Directory created.

Para cualquier usuario que necesite acceder a estos directorios se deberá otorgar los permisos necesarios:
SQL> grant read, write on directory source_dir to ;

Grant succeeded.

SQL> grant read, write on directory target_dir to ;

Grant succeeded.

SQL>

Paso5: Llevando a cabo las transferencias:
BEGIN
 sys.dbms_file_transfer.copy_file(source_directory_object =>
 'SOURCE_DIR', source_file_name => 'nnndf0_full_weekly_0.271.766859353',
 destination_directory_object => 'TARGET_DIR' ,
 destination_file_name => 'MyFullBackupPiece01.bkp');
END;
/
PL/SQL procedure successfully completed.

BEGIN
 sys.dbms_file_transfer.copy_file(source_directory_object =>
 'SOURCE_DIR', source_file_name => 'ncsnf0_full_weekly_0.269.766859431',
 destination_directory_object => 'TARGET_DIR' ,
 destination_file_name => 'MyFullBackupPiece02.bkp');
END;
/
PL/SQL procedure successfully completed.

Visualizacion de archivos (piezas de RMAN) generadas en el sistema operativo
[oracle@MYSERVER-mydb MyExternalFileSystem]$ ls -lt
total 1057452
-rw-r----- 1 oracle dba   10059776 Nov 10 18:08 MyFullBackupPiece01.bkp
-rw-r----- 1 oracle dba 1071702016 Nov 10 18:07 MyFullBackupPiece02.bkp
[oracle@MYSERVER-mydb MyExternalFileSystem]$

Para utilizar las piezas generadas en recuperaciones de nuestra base de datos, debemos catalogar las mismas. Esto se podrá llevar a cabo a través del comando CATALOG de RMAN.
RMAN> catalog start with '/home/oracle/MyExternalFileSystem';

Aplicaciones y uso

Las posibles aplicaciones reales que podemos realizar con transferencias de piezas o archivos desde ASM hacia otros destinos son variadas. Listamos algunas:
  • Transferencia de Archived Redo Logs para resolver casos de GAP para Manual Standby Databases o Data Guard en versiones 10g/11g.
  • Extraer RMAN backups (full, archives, controlfiles, etc...) para procedimientos tales como: RMAN Duplicate, Instanciación de Standby o Data Guard Databases, etc... y otros.
  • Transferencias de ASM a ASM para replicación de BBDDs
  • Y muchas otras mas

viernes, 29 de enero de 2016

Guia Rapida Backups RMAN

1. Objetivos

Manual con ejemplos básicos de uso de RMAN.

1. Conectarse al catalogo de RMAN de una BBDD determinada

[ora11g@prueba ~]$ rman target / catalog rman@rman

Recovery Manager: Release 11.2.0.1.0 - Production on Tue Feb 1 10:00:45 2011

Copyright (c) 1982, 2009, Oracle and/or its affiliates.  All rights reserved.

connected to target database: DBA11G (DBID=337560195)
recovery catalog database Password: *****
connected to recovery catalog database

2. Crear y Configurar un catálogo de recuperación.

2.1. Configurar el catálogo de recuperación de la Base de datos

Conectarse a la BBDD para crear un tablespace nuevo
$ sqlplus /nolog
SQL> connect /as sysdba  
Conectado.
Crear un tablespace
SQL> create tablespace nuevo datafile '/database/dba11g/nuevo.dbf' size 2M autoextend on;
Tablespace creado.              

2.2. Crear el propietario del catálogo de recuperación.

SQL> create user rman   
2  identified by rman   
3  default tablespace nuevo  
4  quota unlimited on nuevo;

SQL> grant connect to rman
SQL> grant recovery_catalog_owner to rman;

2.3. Crear el catálogo de recuperación

$ rman target / catalog rman@rman
rman> create catalog;

3. Sincronizar el catálogo de recuperación

3.1. Registrar una BBDD

$ rman target / catalog rman@rman
RMAN> register database;

3.2. Desregistrar una BBDD

$ Rman target / catalog rman@rman
RMAN> unregister database;

4. Borrar catalog de recuperación

RMAN> connect catalog rman/rman@rman
RMAN> drop catalog;
RMAN> drop catalog;

5. Actualización de versión del catálogo de recuperación.

RMAN> upgrade catalog;

6. Crear y usar un catálogo virtual privado

6.1. Crear el propietario del catálogo virtual privado.

$ sqlplus /nolog
SQL> connect /as sysdba
SQL> create user user_virtual  
2  identified by uservirtual  
3  default tablespace users  
4  quota unlimited on users;

6.2. Otorgar permisos al propietario del catálogo virtual privado.

SQL> grant recovery_catalog_owner to user_virtual;
SQL> grant catalog for database dba11g to user_virtual;
SQL> grant register database to user_virtual;

6.3 Crear un catálogo virtual privado.

$ rman target / catalog user_virtual/uservirtual@rman
RMAN> create virtual catalog;

Nota: Si la versión del cliente rman es anterior a Oracle Database 11g se debe ejecutar la siguiente sentencia:
RMAN> exe rman.dbms_rcvcat.create_virtual_catalog;

6.4 Usar el catálogo virtual privado.

Registramos una base de datos para este catálogo
$ rman target / catalog user_virtual/uservirtual@rman
RMAN> register database;

VIsualizamos las bases de datos registradas
$ sqlplus  user_virtual/user_virtual@rman
SQL> Select distict db_name from dbinc;

7. Backups ( ejemplo con base de datos dba11g )

Nos conectamos a la base de datos contra el catálogo
$ export ORACLE_SID=dba11g$ 
rman target / catalog rman/rman@rman
Recovery Manager: Release 11.2.0.1.0 - Production on Fri Feb 4 09:55:30 2011
Copyright (c) 1982, 2009, Oracle and/or its affiliates.  All rights reserved.
connected to target database: DBA11G (DBID=337560195)
connected to recovery catalog database

7.1 Backup completo de la BBDD (Whole Database Backup)

RMAN> backup as copy database spfile plus archivelog;

7.2 Full Backups

RMAN> backup database spfile plus archivelog;

7.3. Incremental Backups

Level 0 Incremental Backups
RMAN> backup incremental level 0 tablespace users; 

Differential Incremental Backups
RMAN> backup incremental level 1 tablespace users;

7.4 Cumulative Incremental Backups

RMAN> backup incremental level 1 cumulative tablespace users;

7.5 Comprimir backups

RMAN> backup as compressed backupset format ‘/ubicacion/ rman_%d_s%_t%_%p.bkupset’ tablespace users;

RMAN> backup as compressed backupset users;

7.6 Borrar todos los backups

RMAN> delete backup

7.7 Eliminar los backups obsoletos

RMAN> delete obsolete;
RMAN retention policy will be applied to the command
RMAN retention policy is set to recovery window of 1 days
using channel ORA_DISK_1
Deleting the following obsolete backups and copies:
-----
Deleted 17 objects

7.8 Más tipos de backup con RMAN

Backup de toda la base de datos
RMAN> backup database; 

Backup de un tablespace
RMAN> backup tablespace tbs_name;

Backup de un usuario
RMAN> backup user username; 

8. Recover/ Recuperación con RMAN

8.1 Recuperación total de una base de datos


Partimos de un ‘Whole Database Backup’ y se ha borrado toda la base de datos
 RMAN> backup as copy database spfile plus archivelog;

La recuperación se realiza de la siguiente forma:
La base de datos tiene que estar en modo nomount$sqlplus /nolog
SQL> connect /as sysdba
SQL> shutdown abort;  
SQL> startup nomount;

Recuperar la BBDD
RMAN> restore database;  
RMAN> recover database;

Montar la BBDD y abrir la base de datos con un resetlogs
SQL> alter database mount;
SQL> alter database open resetlogs;    

8.2 Recuperación de los controlfile

$ export ORACLE_SID=dba11g
$ rman target/ catalog  rman/rman@rman
RMAN> restore controlfile;

8.3 Comandos generales para recuperar la BBDD

RMAN> restore database;  
RMAN> recover database;

8.4 Comandos para la recuperación a tener en cuenta

recover database until cancel
recover database until time '2004-03-21:22:59:04'
recover database until change 123456

recover datafile 'filename' until cancel
recover datafile 'filename' until time '2004-03-21:22:59:04'
recover datafile 'filename' until change 123456

recover tablespace ts_name until cancel
recover tablespace ts_name until time '2004-03-21:22:59:04'
recover tablespace ts_name until change 123456

recover database using backup controlfile

9. Listar los backups

RMAN> list backup;
LIST BACKUP OF DATAFILE

miércoles, 27 de enero de 2016

Creating Physical Standby Using RMAN DUPLICATE...FROM ACTIVE DATABASE My Oracle Support

Step by step guide on how to create a physical standby database using RMAN DUPLICATE FROM ACTIVE DATABASE command without shutting down the primary and using primary active database files (No need to take a backup)
This is feature available in Oracle11g onwards.
In case you may want or need more about your current topic - please also access the Backup & Recover Community of Customers and Oracle Specialists directly via:
https://community.oracle.com/community/support/oracle_database/database_backup_and_recovery

Database Name :- chicago
Primary db_unique_name :- chicago
standby db_unique_name :- Boston

For duplicating a NON-Standby database, see :
   Note 452868.1 RMAN 'Duplicate From Active Database' Feature in 11G

Solution

1. Make the necessary changes to the primary database.
    a. Enable force logging.
    b. Creating the password file if one does not exist.
    c. Create standby redologs.
    d. Modify the parameter file suitable for Dataguard.
2. Ensure that the sql*net connectivity is working fine.
3. Create the standby database over the network using the active(primary) database files.
    a. Create the password file
    b. Create the initialization parameter file for the standby database (auxiliary database)
    c. Create the necessary mount points or the folders for the database files
    d. Run the standby creation ON STANDBY by connecting to primary as target database.

DUPLICATE TARGET DATABASE 
FOR STANDBY
FROM ACTIVE DATABASE
SPFILE
   PARAMETER_VALUE_CONVERT '', ''
   SET DB_FILE_NAME_CONVERT '', ''
   SET LOG_FILE_NAME_CONVERT '', ''
   SET SGA_MAX_SIZE 200M
   SET SGA_TARGET 125M;
4. Check the log shipping and apply.

PROCEDURE:

While creating the standby database we use the active database files i.e., this command will be useful in creating the physical standby database using active database files over the network.

1. Prepare the production database to be the primary database

a. Ensure that the database is in archivelog mode .
SQL> select log_mode from v$database;

LOG_MODE
------------
ARCHIVELOG

b. Enable force logging
SQL> ALTER DATABASE FORCE LOGGING;

c. Create standby redologs
SQL> alter database add standby logfile '' size ;

d. Modify the primary initialization parameter for dataguard on primary,
SQL> alter system set LOG_ARCHIVE_CONFIG='DG_CONFIG=(chicago,boston)';
System altered.

SQL> alter system set LOG_ARCHIVE_DEST_1='LOCATION=/u01/app/oracle/databases/chicago/redo/ VALID_FOR=(ALL_LOGFILES,ALL_ROLES) DB_UNIQUE_NAME=chicago';
System altered.

SQL> alter system set LOG_ARCHIVE_DEST_2='SERVICE=boston LGWR ASYNC VALID_FOR=(ONLINE_LOGFILES,PRIMARY_ROLE) DB_UNIQUE_NAME=boston';
System altered.

SQL> alter system set LOG_ARCHIVE_DEST_STATE_1=ENABLE;
System altered.

SQL> alter system set FAL_SERVER=boston;
System altered.

SQL> alter system set FAL_CLIENT=chicago;
System altered.

SQL> alter system set DB_FILE_NAME_CONVERT='/u01/app/oracle/databases/boston/data/','/u01/app/oracle/databases/chicago/data' scope=spfile;
System altered.

SQL> alter system set LOG_FILE_NAME_CONVERT='/u01/app/oracle/databases/boston/redo/','/u01/app/oracle/databases/chicago/redo' scope=spfile;
System altered.

2. Ensure that the sql*net connectivity is working fine.

Insert a static entry for Boston in the listener.ora file of the standby system.

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
     (GLOBAL_DBNAME = boston.us.oracle.com)
     (ORACLE_HOME = /u01/app/oracle/product/OraHome111)
     (SID_NAME = boston)
    )
   )

LISTENER =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = )(PORT = 1521))
  )

TNSNAMES.ORA for the Primary and Standby should have BOTH entries

CHICAGO =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = )(PORT = 1521))
    )
    (CONNECT_DATA = (SERVICE_NAME = chicago.us.oracle.com))
  )

BOSTON =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = )(PORT = 1521))
    )
    (CONNECT_DATA = (SERVICE_NAME = boston.us.oracle.com))
  )
Check with the SQL*Net configuration using the following commands on the Primary AND Standby
% tnsping chicago
% tnsping boston

3. Create the standby database

a. Copy the password file from the primary $ORACLE_HOME/dbs and rename it to the standby database name.
The username is required to be SYS and the password needs to be the same on the Primary and Standby.
The best practice for this is to copy the passwordfile as suggested.
The password file name must match the instance name/SID used at the standby site, not the DB_NAME.
b. Create a initialization parameter with only one parameter DB_NAME.
DB_NAME=chicago
DB_UNIQUE_NAME=boston
DB_BLOCK_SIZE=
c. Create the necessary directories in the standby location to place database files and trace files ($ADR_HOME).

d. Set the environment variable ORACLE_SID to the standby service and start the standby-instance.
% export ORACLE_SID=boston
% sqlplus "/ as sysdba"
SQL> startup nomount pfile=$ORACLE_HOME/dbs/initcore1.ora
NOTE : Use either PFILE or SPFILE

# Addtl. comment
# If DUPLICATE without TARGET connection is used you cannot use SPFILE
# else getting

RMAN-05537: DUPLICATE without TARGET connection when auxiliary instance is started with spfile cannot use SPFILE clause

e. Verify if the connection 'AS SYSDBA' is working
% sqlplus /nolog
SQL> connect sys/SQL> connect sys/@chicago AS SYSDBA

f. On the primary system invoke the RMAN executable and connect to the primary and the auxiliary database ( i.e., the standby)
$ rman target sys/sys@chicago auxiliary sys/sys@boston

connected to target database: CHICAGO (DBID=761464750)
connected to auxiliary database: CHICAGO (not mounted)

RMAN> run {
allocate channel prmy1 type disk;
allocate channel prmy2 type disk;
allocate channel prmy3 type disk;
allocate channel prmy4 type disk;
allocate auxiliary channel stby type disk;

duplicate target database for standby from active database
spfile
  parameter_value_convert 'chicago','boston'
  set db_unique_name='boston'
  set db_file_name_convert='/chicago/','/boston/'
  set log_file_name_convert='/chicago/','/boston/'
  set control_files='/u01/app/oracle/oradata/control01.ctl'
  set log_archive_max_processes='5'
  set fal_client='boston'
  set fal_server='chicago'
  set standby_file_management='AUTO'
  set log_archive_config='dg_config=(chicago,boston)'
  set log_archive_dest_2='service=chicago ASYNC valid_for=(ONLINE_LOGFILE,PRIMARY_ROLE) db_unique_name=chicago'
;
}

using target database control file instead of recovery catalog
allocated channel: prmy1
channel prmy1: SID=147 device type=DISK

allocated channel: prmy2
channel prmy2: SID=130 device type=DISK

allocated channel: prmy3
channel prmy3: SID=137 device type=DISK

allocated channel: prmy4
channel prmy4: SID=170 device type=DISK

allocated channel: stby
channel stby: SID=98 device type=DISK

Starting Duplicate Db at 19-MAY-08

contents of Memory Script:
{
backup as copy reuse
file '/u02/app/oracle/product/11.1.0/db_1/dbs/orapwcore' auxiliary format'/u02/app/oracle/product/11.1.0/db_1/dbs/orapwcore1'
file'/u02/app/oracle/product/11.1.0/db_1/dbs/spfilecore.ora' auxiliary format'/u02/app/oracle/product/11.1.0/db_1/dbs/spfilecore1.ora' ;
sql clone "alter system set spfile= ''/u02/app/oracle/product/11.1.0/db_1/dbs/spfilecore1.ora''";
}
executing Memory Script

Starting backup at 19-MAY-08
Finished backup at 19-MAY-08

sql statement: alter system set spfile= ''/u02/app/oracle/product/11.1.0/db_1/dbs/spfilecore1.ora''

contents of Memory Script:
{
sql clone "alter system set audit_file_dest =''/u02/app/oracle/admin/boston/adump'' comment='''' scope=spfile";
sql clone "alter system set dispatchers =''(PROTOCOL=TCP) (SERVICE=core1XDB)'' comment='''' scope=spfile";
sql clone "alter system set log_archive_dest_2 =''service=core11 arch async VALID_FOR=(ONLINE_LOGFILES,PRIMARY_ROLE) db_unique_name=boston'' comment='''' scope=spfile";
sql clone "alter system set db_unique_name =''boston'' comment='''' scope=spfile";
sql clone "alter system set db_file_name_convert =''/chicago/'', ''/boston/'' comment='''' scope=spfile";
sql clone "alter system set log_file_name_convert =''/chicago/'', ''/boston/'' comment='''' scope=spfile";
sql clone "alter system set control_files =''/u01/app/oracle/oradata/control01.ctl'' comment='''' scope=spfile";
sql clone "alter system set log_archive_max_processes =5 comment='''' scope=spfile";
sql clone "alter system set fal_client =''boston'' comment='''' scope=spfile";
sql clone "alter system set fal_server =''chicago'' comment='''' scope=spfile";
sql clone "alter system set standby_file_management =''AUTO'' comment='''' scope=spfile";
sql clone "alter system set log_archive_config =''dg_config=(chicago,boston)'' comment='''' scope=spfile";
sql clone "alter system set log_archive_dest_2 =''service=chicago ASYNC valid_for=(ONLINE_LOGFILE,PRIMARY_ROLE) db_unique_name=chicago'' comment='''' scope=spfile";
shutdown clone immediate;
startup clone nomount ;
}
executing Memory Script

sql statement: alter system set audit_file_dest = ''/u02/app/oracle/admin/boston/adump'' comment= '''' scope=spfile
sql statement: alter system set dispatchers = ''(PROTOCOL=TCP) (SERVICE=core1XDB)'' comment= '''' scope=spfile
sql statement: alter system set log_archive_dest_2 = ''service=core11 arch async VALID_FOR=(ONLINE_LOGFILES,PRIMARY_ROLE) db_unique_name=boston'' comment= '''' scope=spfile
sql statement: alter system set db_unique_name = ''boston'' comment= '''' scope=spfile
sql statement: alter system set db_file_name_convert = ''/chicago/'', ''/boston/'' comment= '''' scope=spfile
sql statement: alter system set log_file_name_convert = ''/chicago/'', ''/boston/'' comment= '''' scope=spfile
sql statement: alter system set control_files = ''/u01/app/oracle/oradata/control01.ctl'' comment= '''' scope=spfile
sql statement: alter system set log_archive_max_processes = 5 comment= '''' scope=spfile
sql statement: alter system set fal_client = ''boston'' comment= '''' scope=spfile
sql statement: alter system set fal_server = ''chicago'' comment= '''' scope=spfile
sql statement: alter system set standby_file_management = ''AUTO'' comment= '''' scope=spfile
sql statement: alter system set log_archive_config = ''dg_config=(chicago,boston)'' comment= '''' scope=spfile
sql statement: alter system set log_archive_dest_2 = ''service=chicago ASYNC valid_for=(ONLINE_LOGFILE,PRIMARY_ROLE) db_unique_name=chicago'' comment= '''' scope=spfile

Oracle instance shut down

connected to auxiliary database (not started)
Oracle instance started

Total System Global Area 845348864 bytes

Fixed Size 1303188 bytes
Variable Size 482348396 bytes
Database Buffers 356515840 bytes
Redo Buffers 5181440 bytes

contents of Memory Script:
{
backup as copy current controlfile for standby auxiliary format '/u01/app/oracle/oradata/control01.ctl';
sql clone 'alter database mount standby database';
}
executing Memory Script

Starting backup at 19-MAY-08
channel prmy1: starting datafile copy
copying standby control file
output file name=/u02/app/oracle/product/11.1.0/db_1/dbs/snapcf_chicago.f tag=TAG20080519T173406 RECID=2 STAMP=655148053
channel prmy1: datafile copy complete, elapsed time: 00:00:03
Finished backup at 19-MAY-08

sql statement: alter database mount standby database

contents of Memory Script:
{
set newname for tempfile 1 to"/u02/app/oracle/oradata/boston/temp01.dbf";
switch clone tempfile all;
set newname for datafile 1 to "/u02/app/oracle/oradata/boston/system01.dbf";
set newname for datafile 2 to "/u02/app/oracle/oradata/boston/sysaux01.dbf";
set newname for datafile 3 to "/u02/app/oracle/oradata/boston/undotbs01.dbf";
set newname for datafile 4 to "/u02/app/oracle/oradata/boston/users01.dbf";
backup as copy reuse
datafile 1 auxiliary format "/u02/app/oracle/oradata/boston/system01.dbf"
datafile 2 auxiliary format "/u02/app/oracle/oradata/boston/sysaux01.dbf"
datafile 3 auxiliary format "/u02/app/oracle/oradata/boston/undotbs01.dbf"
datafile 4 auxiliary format "/u02/app/oracle/oradata/boston/users01.dbf" ;
sql 'alter system archive log current';
}
executing Memory Script

executing command: SET NEWNAME

renamed tempfile 1 to /u02/app/oracle/oradata/boston/temp01.dbf in control file

executing command: SET NEWNAME
executing command: SET NEWNAME
executing command: SET NEWNAME
executing command: SET NEWNAME

Starting backup at 19-MAY-08
channel prmy1: starting datafile copy
input datafile file number=00001 name=/u02/app/oracle/oradata/chicago/system01.dbf
channel prmy2: starting datafile copy
input datafile file number=00002 name=/u02/app/oracle/oradata/chicago/sysaux01.dbf
channel prmy3: starting datafile copy
input datafile file number=00003 name=/u02/app/oracle/oradata/chicago/undotbs01.dbf
channel prmy4: starting datafile copy
input datafile file number=00004 name=/u02/app/oracle/oradata/chicago/users01.dbf
output file name=/u02/app/oracle/oradata/boston/undotbs01.dbf tag=TAG20080519T173421 RECID=0 STAMP=0
channel prmy3: datafile copy complete, elapsed time: 00:00:24
output file name=/u02/app/oracle/oradata/boston/users01.dbf tag=TAG20080519T173421 RECID=0 STAMP=0
channel prmy4: datafile copy complete, elapsed time: 00:00:16
output file name=/u02/app/oracle/oradata/boston/system01.dbf tag=TAG20080519T173421 RECID=0 STAMP=0
channel prmy1: datafile copy complete, elapsed time: 00:02:32
output file name=/u02/app/oracle/oradata/boston/sysaux01.dbf tag=TAG20080519T173421 RECID=0 STAMP=0
channel prmy2: datafile copy complete, elapsed time: 00:02:32
Finished backup at 19-MAY-08

sql statement: alter system archive log current

contents of Memory Script:
{
switch clone datafile all;
}
executing Memory Script

datafile 1 switched to datafile copy
input datafile copy RECID=2 STAMP=655148231 file name=/u02/app/oracle/oradata/boston/system01.dbf
datafile 2 switched to datafile copy
input datafile copy RECID=3 STAMP=655148231 file name=/u02/app/oracle/oradata/boston/sysaux01.dbf
datafile 3 switched to datafile copy
input datafile copy RECID=4 STAMP=655148231 file name=/u02/app/oracle/oradata/boston/undotbs01.dbf
datafile 4 switched to datafile copy
input datafile copy RECID=5 STAMP=655148231 file name=/u02/app/oracle/oradata/boston/users01.dbf
Finished Duplicate Db at 19-MAY-08
released channel: prmy1
released channel: prmy2
released channel: prmy3
released channel: prmy4

4. Start managed recovery

Connect to standby using SQL*Plus and start the MRP (Managed Recovery Process). Compare the primary last sequence and MRP (Managed Recovery Process) applying sequence.
Example :
SQL> alter database recover managed standby database disconnect from session;

5. Open standby database in Read Only (active dataguard)

If you are licensed to use Active Dataguard (ADG) than open the Standby Database in READ ONLY and start the recovery.
SQL> alter database recover managed standby database cancel;
SQL> alter database open;
SQL> alter database recover managed standby database disconnect;

Configuracion Dataguard 11g My Oracle Support

Pre-Requisitea) Database (PRIMARY) is up and running and the datafiles, controlfiles residing in ASM.
b) ASM instance and diskgroups configured in STANDBY server.
c) Network connectivity between PRIMARY and STANDBY server
PROCEDURE
1.Enable force logging in PRIMARY.
2.Create SRL(standby redo logs) in PRIMARY.
3.Backup the PRIMARY database.
4.Make proper changes in the parameter file of PRIMARY.
5.Create the parameter file for STANDBY
6.Copy the files (RMAN Backup, init.ora) to STANDBY
7.Establish the connectivity between PRIMARY and STANDBY.
8.Start the STANDBY instance and use RMAN duplicate to create standby database
9. Create SRL on standby.
10.Start the MRP process,
11. Verify whether the log are shipped and applied properly @the standby


Consider two databases of names PRIMARY= PRIMA  and STANDBY= MYSTD

1. Enable Forced Logging on PRIMARY

SQL> ALTER DATABASE FORCE LOGGING;

2. Configure Standby Redo Log on PRIMARY
NOTE:SIZE OF STANDBY LOGFILE SHOULD BE SAME AS ONLINE LOGFILE

a. Check the log files and sizes,

SQL>SELECT GROUP#,BYTES FROM V$LOG;

b. Create SRL
ALTER DATABASE ADD STANDBY LOGFILE GROUP 4 SIZE 100M;
NOTE: The SRL will be created in the ASM Disk group mentioned in init.ora parameter DB_CREATE_ONLINE_LOG_DEST_1
c. Verify the standby redo log file groups were created(do this after the creation of standby database)

SQL> SELECT GROUP#,THREAD#,SEQUENCE#,ARCHIVED,STATUS FROM V$STANDBY_LOG;

3. Use RMAN to backup PRIMARY database with archivelog & controlfile.

RMAN> backup database format '/tmp/dbbkp/PRIMA_%U';
RMAN> backup archivelog all format '/tmp/dbbkp/PRIMA_ARC_%U';
RMAN> backup current controlfile for standby format '/tmp/dbbkp/PRIMA_CONTROL.bkp';

4. Make the necessary changes to PRIMARY  .

DB_NAME=PRIMA
DB_UNIQUE_NAME=PRIMA
LOG_ARCHIVE_CONFIG='DG_CONFIG=(PRIMA,MYSTD)'
LOG_ARCHIVE_DEST_2= 'SERVICE=stdby LGWR ASYNC VALID_FOR=(ONLINE_LOGFILES,PRIMARY_ROLE) DB_UNIQUE_NAME=MYSTD'
LOG_ARCHIVE_DEST_STATE_2=DEFER
REMOTE_LOGIN_PASSWORDFILE=EXCLUSIVE
LOG_ARCHIVE_FORMAT=%t_%s_%r.arc
LOG_ARCHIVE_MAX_PROCESSES=30
FAL_SERVER=MYSTD
FAL_CLIENT=PRIMA
DB_FILE_NAME_CONVERT='MYSTD','PRIMA'
LOG_FILE_NAME_CONVERT='MYSTD','PRIMA'
STANDBY_FILE_MANAGEMENT=AUTO


5. Create the parameter file for standby,

a. CREATE PFILE='' from spfile; (@primary,)
b. Make the necessary changes, for example,

DB_NAME=PRIMA
DB_UNIQUE_NAME=MYSTD
LOG_ARCHIVE_CONFIG='DG_CONFIG=(PRIMA,MYSTD)'
CONTROL_FILES='+DATA','+FRA'
DB_FILE_NAME_CONVERT='PRIMA','MYSTD'
LOG_FILE_NAME_CONVERT='PRIMA','MYSTD'
LOG_ARCHIVE_FORMAT=log%t_%s_%r.arc
LOG_ARCHIVE_DEST_2= 'SERVICE=PRIMA LGWR ASYNC VALID_FOR=(ONLINE_LOGFILES,PRIMARY_ROLE) DB_UNIQUE_NAME=PRIMA'
LOG_ARCHIVE_DEST_STATE_1=ENABLE
LOG_ARCHIVE_DEST_STATE_2=ENABLE
REMOTE_LOGIN_PASSWORDFILE=EXCLUSIVE
STANDBY_FILE_MANAGEMENT=AUTO
FAL_SERVER=PRIMA
FAL_CLIENT=MYSTD

Note: If the ASM Disk groups names are different between PRIMARY and STANDBY do the necessary changes in STANDBY with the parameters DB_CREATE_FILE_DEST and DB_CREATE_ONLINE_LOG_DEST_n
6. Copy the files (RMAN Backup, init.ora) to STANDBY
a) Copy the RMAN backup files created in /tmp/dbbkp (step3) to STANDBY in identical location
Example:scp /tmp/dbbkp/* oracle@core1:/tmp/dbbkp/*
b) Copy the init.ora (step 5) to STANDBY
c) Recreate the password file in standby using orapwd utility


7. Establish the connectivity between primary and standby.

In PRIMARY (TNSNAMES.ORA)

MYSTD=
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = 192.9.200.108)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = MYSTD.server.com)
)
)

In STANDBY (TNSNAMES.ORA)
PRIMA=
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = 192.9.200.107)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = PRIMA.server.com)
)
)
NOTE: Use TNSPING to check the connectivity between PRIMARY and STANDBY

8. Start the STANDBY instance and use RMAN duplicate to create standby database

NOTE: Make sure the ASM instance also running.
$export ORACLE_SID=MYSTD
SQL>create spfile from pfile=’
SQL>startup nomount 

NOTE: Connect to catalog if your primary database has catalog database.
$RMAN target sys/@primary catalog RMAN/RMAN@RMAN auxiliary sys/
RMAN> RUN {
allocate auxiliary channel C1 device type disk;
duplicate target database for standby;
}

9. Create SRL(Standby Redo logs) on standby,
NOTE:SIZE OF STANDBY LOGFILE SHOULD BE SAME AS ONLINE LOGFILE

For Example,

ALTER DATABASE ADD STANDBY LOGFILE GROUP 4 SIZE 100M;

10. Start the MRP process in PRIMARY

In PRIMARY

SQL>ALTER SYSTEM SET LOG_ARCHIVE_DEST_STATE_2=ENABLE;

In STANDBY
SQL>ALTER DATABASE RECOVER MANAGED STANDBY DATABASE DISCONNECT FROM SESSION;

11. Verify whether the log are shipped and applied properly in the standby

a. execute on PRIMARY database

SQL> ALTER SYSTEM SWITCH LOGFILE;

b. execute on STANDBY database

SQL> SELECT SEQUENCE#, FIRST_TIME, NEXT_TIME FROM V$ARCHIVED_LOG ORDER BY SEQUENCE#;

c. Issue more log switches at PRIMARY

SQL> ALTER SYSTEM SWITCH LOGFILE;

d. Verify the new redo data was archived on the standby database.On the standby database, query the V$ARCHIVED_LOG view to verify the redo data was received and archived on the standby database:

SQL> SELECT SEQUENCE#, FIRST_TIME, NEXT_TIME  FROM V$ARCHIVED_LOG ORDER BY SEQUENCE#;

NOTE: Verify new archived redo log files were applied. At the standby database, query the V$ARCHIVED_LOG view to verify the archived redo log files were applied.

SQL> SELECT SEQUENCE#,APPLIED FROM V$ARCHIVED_LOG ORDER BY SEQUENCE#;

Duplicate a Database Using RMAN in Oracle Database 11g Release 2

Duplicate a Database Using RMAN in Oracle Database 11g Release 2


RMAN> catalog start with '/u01/backups/rman/2016-01-21/' noprompt

This article is an update of a previous Oracle 9i article.
Related articles.

Introduction

RMAN has the ability to duplicate, or clone, a database from a backup or from an active database. It is possible to create a duplicate database on a remote server with the same file structure, a remote server will a different file structure or the local server with a different file structure.
The article assumes the duplicate database is being created on a separate server, using the same SID (DB11G) and the same file structure as the source database. Explanations of several other scenarios are available here.

Backup-Based Duplication

Create a backup of the source database, if a suitable one doesn't already exist.
$ rman target=/

RMAN> CONFIGURE CONTROLFILE AUTOBACKUP ON;
RMAN> BACKUP DATABASE PLUS ARCHIVELOG
All subsequent actions occur on the server running the duplicate database.
Create a password file for the duplicate instance.
$ orapwd file=/u01/app/oracle/product/11.2.0/db_1/dbs/orapwDB11G password=password entries=10
Add the appropriate entries into the "tnsnames.ora" file in the "$ORACLE_HOME/network/admin" directory to allow connections to the target database from the duplicate server.
# Added to the tnsnames.ora
DB11G-SOURCE =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = ol5-112-dup1)(PORT = 1521))
    )
    (CONNECT_DATA =
      (ORACLE_SID = DB11G)
    )
  )
Create a PFILE for the duplicate database. Since we are duplicating the database onto a separate server with the same filesystem as the original, we don't need to convert the file names. In this case, the PFILE is called "initDB11G.ora" and is placed in the "$ORACLE_HOME/dbs" directory.
# Minimum Requirement.
DB_NAME=DB11G

# Convert file names to allow for different directory structure if necessary.
#DB_FILE_NAME_CONVERT='/u01/app/oracle/oradata/DB11G/','/u01/app/oracle/oradata/NEWSID/'
#LOG_FILE_NAME_CONVERT='/u01/app/oracle/oradata/DB11G/','/u02/app/oracle/oradata/NEWSID/'
We don't need all the other parameters as the clone will copy the SPFILE from the primary database. If you are duplicating a database on the same machine you will probably need to create a PFFILE/SPFILE manually from the primary database SPFILE, manually change the values and avoid the SPFILE clause in the duplicate command.
Create any directories necessary for start the duplicate database.
$ mkdir -p /u01/app/oracle/oradata/DB11G
$ mkdir -p /u01/app/oracle/fast_recovery_area/DB11G
$ mkdir -p /u01/app/oracle/admin/DB11G/adump
Make the backup files from the source database available to the destination server. That can be done by either copying them to the matching location on the destination server, or placing them on a shared drive. If you are copying the files, you may want to use the following type of commands.
$ scp -r oracle@ol5-112-dup1:/u01/app/oracle/fast_recovery_area/DB11G/archivelog /u01/app/oracle/fast_recovery_area/DB11G
$ scp -r oracle@ol5-112-dup1:/u01/app/oracle/fast_recovery_area/DB11G/backupset /u01/app/oracle/fast_recovery_area/DB11G
$ scp -r oracle@ol5-112-dup1:/u01/app/oracle/fast_recovery_area/DB11G/autobackup /u01/app/oracle/fast_recovery_area/DB11G
Connect to the duplicate instance.
$ ORACLE_SID=DB11G; export ORACLE_SID
$ sqlplus / as sysdba
Start the database in NOMOUNT mode.
SQL> STARTUP NOMOUNT;
With the duplicate database started we can now connect to it from RMAN. For the duplication to work we must connect to the duplicate database (AUXILIARY), but depending on the type of duplication we are doing we may optionally connect to the original database (TARGET) and/or the recovery catalog (CATALOG).
$ ORACLE_SID=DB11G; export ORACLE_SID

# No target or catalog. Metadata comes from backups.
$ rman AUXILIARY /

# Target, but no catalog. Metadata comes from target database controlfile.
$ rman TARGET sys/password@DB11G-SOURCE AUXILIARY /

# Catalog, but no target. Metadata comes from the RMAN catalog.
$ rman CATALOG rman/password@rman-catalog AUXILIARY /

# Target and catalog. Metadata can come from the target controlfile or the catalog.
$ rman TARGET sys/password@DB11G-SOURCE CATALOG rman/password@rman-catalog AUXILIARY /
We can then duplicate the database using one of the following commands. Remember, remove the SPFILE clause if you have manually created a full PFILE or SPFILE.
# Backup files are in matching location to that on the source server.
# Duplicate database to TARGET's current state.
DUPLICATE TARGET DATABASE TO DB11G
  SPFILE
  NOFILENAMECHECK;

# Duplicate database to TARGET's state 4 days ago.
DUPLICATE TARGET DATABASE TO DB11G
  UNTIL TIME 'SYSDATE-4'
  SPFILE
  NOFILENAMECHECK;

# Backup files are in a different location to that on the source server.
# Duplicate database to the most recent state possible using the provided backups.
# Works with just an AUXILIARY connection only.
DUPLICATE DATABASE TO DB11G
  SPFILE
  BACKUP LOCATION '/source/app/oracle/fast_recovery_area/DB11G'
  NOFILENAMECHECK;

# Do a point-in-time clone.
DUPLICATE DATABASE TO DB11G
  SPFILE
  BACKUP LOCATION '/source/app/oracle/fast_recovery_area/DB11G'
  NOFILENAMECHECK
  UNTIL TIME "TO_DATE('2014-11-17 07:00:00', 'YYYY-MM-DD HH24:MI:SS')";

# Alter some SPFILE parameters during the clone.
DUPLICATE DATABASE TO MYCLONE
  SPFILE
    parameter_value_convert ('DB11G','MYCLONE')
    set db_file_name_convert='/u01/oradata/db11g/','/u01/oradata/myclone/'
    set log_file_name_convert='/u01/oradata/db11g/','/u01/oradata/myclone/'
    set control_files='/u01/oradata/myclone/control01.ctl','/u01/oradata/myclone//control02.ctl','/u01/oradata/myclone/control03.ctl'
    set db_name='MYCLONE'
    set log_archive_dest_1='location=/u01/oradata/myclone/arch'
  BACKUP LOCATION '/source/app/oracle/fast_recovery_area/DB11G'
  NOFILENAMECHECK;

The time it takes to complete varies depending on the size of the database and the specification of the server. Once the process is finished RMAN produces a completion message and you have your duplicate instance.

Active Database Duplication



Oracle 11g introduced the ability to create duplicate databases directly without the need for a backup. This is known as active database duplication. The process is similar to the backup-based duplication, with a few exceptions.
First, and most obviously, you don't need a backup of the source system, but it does have to be in ARCHIVELOG mode.
The passwords in the password files must match for both servers, so remember to set the correct password when creating the password file on the destination server.
Both the source and destination database servers require a "tnsnames.ora" entry for the destination database. In this case I added the following to each server. The destination server still requires the source entry shown in the previous section.
# Added to the tnsnames.ora on source and destination server.
DB11G-DESTINATION =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = ol5-112-dup2)(PORT = 1521))
    )
    (CONNECT_DATA =
      (ORACLE_SID = DB11G)
    )
  )
The destination server requires static listener configuration in a "listener.ora" file. In this case I used the following configuration. Remember to restart or reload the listener.
SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (GLOBAL_DBNAME = DB11G.WORLD)
      (ORACLE_HOME = /u01/app/oracle/product/11.2.0/db_1)
      (SID_NAME = DB11G)
    )
  )

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = ol5-112-dup2.localdomain)(PORT = 1521))
    )
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
  )

ADR_BASE_LISTENER = /u01/app/oracle
When connecting to RMAN, you must use a connect string for both the target and auxiliary connections.
$ ORACLE_SID=DB11G; export ORACLE_SID

$ rman TARGET sys/password@DB11G-SOURCE AUXILIARY sys/password@DB11G-DESTINATION
Include the FROM ACTIVE DATABASE clause in the DUPLICATE command.
DUPLICATE DATABASE TO DB11G
  FROM ACTIVE DATABASE
  SPFILE
  NOFILENAMECHECK;

miércoles, 20 de enero de 2016

How to solve ORA-04044: procedure, function, package, Script .sh

How to solve ORA-04044: procedure, function, package, or type is not allowed here

While creating shell script some time we face error

ORA-04044: procedure, function, package, or type is not allowed here

NOTE:
this is because we are using tables containing '$' SYMBOL and when ever we use tables like v$session,v$log,v$logfile etc shell script take '$' SYMBOL as shell variables and then while reading script it gives error

ORA-04044: procedure, function, package, or type is not allowed here

SOLUTION:-

for overcome this error always use escape '\' SYMBOL before '$' SYMBOL in table name

like we are use

select * from v$session;
select * from v$log;

in shell script we have to use

select * from v\$session;
select * from v\$log;

and this will solve our error and sucessfully run our shell script.

lunes, 18 de enero de 2016

Control_file_record_keep_time

RMAN and control_file_record_keep_time
If the control_file_record_keep_time is less than the retention policy then it may overwrite reusable records prior to obsoleting them in the RMAN metadata. Therefore it is recommended that the control_file_record_keep_time should set to a higher value than the RMAN retention policy.  Hence:

control_file_record_keep_time = retention period + level 0 backup interval + 1

For example, a level 0 backup once a week with retention policy of a recovery windows of 14 days would have a control_file_record_keep_time of 22 ( 14+7+1).

 
SQL> alter system set control_file_record_keep_time=30 scope=both;

System altered.

SQL> show parameter control;

NAME      TYPE VALUE
------------------------------------ ----------- ------------------------------
control_file_record_keep_time      integer 30
control_files      string +DATA/ACME/CONTROLFILE/current
.261.848598131, +FRA/ACME/CONT
ROLFILE/current.256.848598131
control_management_pack_access      string DIAGNOSTIC+TUNING
SQL> 

martes, 12 de enero de 2016

Data Encryption - DBMS_OBFUSCATION_TOOLKIT Security

Create the Package

First we create the package header containing the two conversion functions.
CREATE OR REPLACE PACKAGE toolkit AS

  FUNCTION encrypt (p_text  IN  VARCHAR2) RETURN RAW;
  
  FUNCTION decrypt (p_raw  IN  RAW) RETURN VARCHAR2;
  
END toolkit;
/

Create the Package Body

All VARCHAR2 inputs are padded to multiples of 8 charaters, with the encryption key also being a multiple of 8 charaters. The encryption key and padding characters can be altered to suit.
CREATE OR REPLACE PACKAGE BODY toolkit AS

  g_key     RAW(32767)  := UTL_RAW.cast_to_raw('12345678');
  g_pad_chr VARCHAR2(1) := '~';

  PROCEDURE padstring (p_text  IN OUT  VARCHAR2);


  -- --------------------------------------------------
  FUNCTION encrypt (p_text  IN  VARCHAR2) RETURN RAW IS
  -- --------------------------------------------------
    l_text       VARCHAR2(32767) := p_text;
    l_encrypted  RAW(32767);
  BEGIN
    padstring(l_text);
    DBMS_OBFUSCATION_TOOLKIT.desencrypt(input          => UTL_RAW.cast_to_raw(l_text),
                                        key            => g_key,
                                        encrypted_data => l_encrypted);
    RETURN l_encrypted;
  END;
  -- --------------------------------------------------



  -- --------------------------------------------------
  FUNCTION decrypt (p_raw  IN  RAW) RETURN VARCHAR2 IS
  -- --------------------------------------------------
    l_decrypted  VARCHAR2(32767);
  BEGIN
    DBMS_OBFUSCATION_TOOLKIT.desdecrypt(input => p_raw,
                                        key   => g_key,
                                        decrypted_data => l_decrypted);
                                        
    RETURN RTrim(UTL_RAW.cast_to_varchar2(l_decrypted), g_pad_chr);
  END;
  -- --------------------------------------------------


  -- --------------------------------------------------
  PROCEDURE padstring (p_text  IN OUT  VARCHAR2) IS
  -- --------------------------------------------------
    l_units  NUMBER;
  BEGIN
    IF LENGTH(p_text) MOD 8 > 0 THEN
      l_units := TRUNC(LENGTH(p_text)/8) + 1;
      p_text  := RPAD(p_text, l_units * 8, g_pad_chr);
    END IF;
  END;
  -- --------------------------------------------------

END toolkit;
/

Test It

We can test the basic functionality using the following code.
DECLARE
  l_value VARCHAR2(16) := 'ORACLE-BASE';
  l_raw   RAW(16);
BEGIN
  DBMS_OUTPUT.put_line('l_value: ' || l_value);
  l_raw := toolkit.encrypt(l_value);
  DBMS_OUTPUT.put_line('l_raw: ' || l_raw);
  DBMS_OUTPUT.put_line('Original Value : ' || toolkit.decrypt(l_raw));
END;
/
Remember that the length of the output from the encryption routine will be rounded up to the next multiple of 8 characters. If the results are to be stored as RAW datatypes in the database you must make sure enough room is allocated. SQL*Plus displays the contents of RAW variable in HEX so it appears to be twice as long as it actually is.

Encrypt Table Data

The following code provides a simple example of how data in a table might be encrypted using a trigger. First we must create a test table with an appropriate trigger.
CREATE TABLE encrypted_data (
  username  VARCHAR2(20),
  data      RAW(16)
);

CREATE OR REPLACE TRIGGER encrypted_data_biur_trg 
BEFORE INSERT OR UPDATE ON encrypted_data
FOR EACH ROW
DECLARE
BEGIN
  :new.data := toolkit.encrypt(UTL_RAW.cast_to_varchar2(:new.data));
END;
/
Next we test the trigger using some simple insert, update and query statements.
SQL> INSERT INTO encrypted_data (username, data)
  2  VALUES ('tim_hall', UTL_RAW.cast_to_raw('My Secret Data'));

1 row created.

SQL> SELECT * FROM encrypted_data;

USERNAME             DATA
-------------------- ----------------------------------------
tim_hall             FA57C55510D258C73DE93059E3DC49EC

1 row selected.

SQL> COLUMN data FORMAT A40
SQL> SELECT username, toolkit.decrypt(data) AS data FROM encrypted_data;

USERNAME             DATA
-------------------- ----------------------------------------
tim_hall             My Secret Data

1 row selected.

SQL> UPDATE encrypted_data
  2  SET    data     = UTL_RAW.cast_to_raw('My NEW Secret')
  3  WHERE  username = 'tim_hall';

1 row updated.

SQL> COLUMN data FORMAT A40
SQL> SELECT username, toolkit.decrypt(data) AS data FROM encrypted_data;

USERNAME             DATA
-------------------- ----------------------------------------
tim_hall             My NEW Secret

1 row selected.

SQL>

jueves, 7 de enero de 2016

show snapshot controlfile name

RMAN> show snapshot controlfile name;
Configure it to the shared disk group as below:
[oracle@db2 bin]$ rman target /
Recovery Manager: Release 11.2.0.3.0 - Production on Tue Jul 29 01:30:42 2014
Copyright (c) 1982, 2011, Oracle and/or its affiliates.  All rights reserved.
connected to target database: PDB (DBID=518531946)

RMAN> CONFIGURE SNAPSHOT CONTROLFILE NAME TO '+data/snapcf.f';

using target database control file instead of recovery catalog
old RMAN configuration parameters:
CONFIGURE SNAPSHOT CONTROLFILE NAME TO '/u01/app/oracle/product/11.2.0.3/dbhome_1/dbs/snapcf_PROD021.f';
new RMAN configuration parameters:
CONFIGURE SNAPSHOT CONTROLFILE NAME TO '+data/snapcf.f';
new RMAN configuration parameters are successfully stored

miércoles, 6 de enero de 2016

.PROFILE GRID


#
# Simple profile places /usr/bin at front, followed by /usr/sbin.
#
# Use less(1) or more(1) as the default pager for the man(1) command.
#
export PATH=/usr/bin:/usr/sbin
if [ -f /usr/bin/less ]; then
    export PAGER="/usr/bin/less -ins"
elif [ -f /usr/bin/more ]; then
    export PAGER="/usr/bin/more -s"
fi
#
# Define default prompt to @:<"($|#) ">
# and print '#' for user "root" and '$' for normal users.
#
# Currently this is only done for bash/pfbash(1).
#

case ${SHELL} in
*bash)
    typeset +x PS1="\u@\h:\w\\$ "
    ;;
esac
export AWT_TOOLKIT=XToolkit
export ORACLE_BASE=/u01/app/grid
export ORACLE_HOME=/u01/app/oracle/product/11.2.0/grid_1
export ORACLE_SID=+ASM1
export PATH=$ORACLE_HOME/bin:$ORACLE_HOME/OPatch:$PATH:/usr/sbin:/usr/X11/bin:/usr/dt/bin:/usr/openwin/bin:/usr/sfw/bin:/usr/sfw/sbin:/usr/ccs/bin:/usr/local/bin:/usr/local/sbin:
export LD_LIBRARY_PATH=$ORACLE_HOME/lib:/usr/dt/lib:$ORACLE_HOME/oracm/lib
export CLASSPATH=${CLASSPATH}:$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib:$ORACLE_HOME/network/jlib
export TEMP=/tmp
export TMPDIR=/tmp
ulimit -n 65536

# Alias
alias sql='sqlplus / as sysasm'

lunes, 28 de diciembre de 2015

Oracle Database 11g: "Client Failover" en "Standby Databases" ( Part I )

Oracle Database 11g: "Client Failover" en "Standby Databases" ( Part I )

Por Joel Pérez  & Mahir M. Quluzade
Publicado en Septiembre 2015

Reciban estimados tecnólogos Oracle un cordial saludo. A través del presente artículo, tendremos la oportunidad de tratar un tema de gran importancia como lo es el concepto de “Client Failover” en ambientes de bases de datos “Standby”
Introducción
En repetidas ocasiones cuando analizamos infraestructuras e implantaciones de clientes, una de las primeras actividades que realizamos es el chequeo de cómo las buenas practicas están implementadas o si realmente lo están.
Al momento de realizarlo en materia de “Standby Databases”. Siempre hacemos una pregunta típica: ¿Cual es procedimiento o método que aplican/usan para manejar las conexiones de aplicaciones al momento en que se ha llevado a cabo un “Switchover” o “Failover”?
Las respuestas son diversas, la más típica en muchos casos es:
“...como casi nunca realizamos “Switchover” y mucho menos “Failover” es poco común que tengamos que re-direccionar las conexiones de nuestras aplicaciones.. por lo tanto dado el momento en que tengamos que realizar dicha operación, nos dirigimos al servidor de aplicaciones, allí editamos de forma manual el “Tnsentry” que direcciona a nuestra base de datos de producción, y lo cambiaremos para que direccione posteriormente al servidor “Standby”... en el cual estará operando la base de datos con rol primario”
En líneas generales muchos clientes aplican métodos manuales para re-direccionar sus aplicaciones hacia servidores con bases de datos “Standby”, una vez efectuada una operación de tipo “Switchover” o “Failover”.
Antes de ir mas allá en este tema hay una pregunta que deberían hacerse todos los DBAs que implantan soluciones de “Standby Databases”/”Data Guard”. Los productos Oracle gozan de un nivel elevado en tecnicismo y mas aun cuando estos poseen diversas versiones de desarrollo tal como el tema relacionado con “Standby Databases”/”Data Guard”. La pregunta seria la siguiente: Si las soluciones mencionadas poseen alto tecnicismo para realizar operaciones de “Switchover”/”Failover” y mas, ¿“Oracle Corp.” dejaría de lado el desarrollo o disponibilidad de un modo para que las aplicaciones puedan estar en alta escalabilidad con lo mencionado anteriormente?
La respuesta para el caso es: Si, “Oracle Corp” posee solución y modo para ello, lo mismo es denominado “Client Failover” para conexiones de aplicaciones. El concepto referido a “Client Failover” no está basado solo para el contexto de “Data Guard”.
Para mayor información al respecto les dejamos acá unos enlaces en cual podrán abarcar en forma profunda toda la información al respecto:
Client Failover Best Practices for Highly Available Oracle Databases: Oracle Database 11g Release 2
http://www.oracle.com/technetwork/database/features/availability/maa-wp-11gr2-client-failover-173305.pdf
Client Failover Best Practices for Highly Available Oracle Databases Oracle Database 12c
http://www.oracle.com/technetwork/database/availability/client-failover-2280805.pdf
How To Configure Client Failover For Dataguard Connections Using Database Services
El objetivo de este artículo es exponer de forma breve y efectiva una de las principales técnicas para conseguir implementar “Client Failover” en solución “Data Guard”. A través de los enlaces proporcionados, usted podrá abarcar el tema en un contexto general.
Iniciemos…
En la siguiente figura se expone una configuración típica de una solución “Data Guard”

Los primeros cambios a ser aplicados serán para los archivos “tnsnames.ora” & “sqlnet.ora” de servidores y clientes. En la figura podemos visualizar un servidor con IP: 192.168.56.146 el cual funge conceptualmente como servidor primario y el segundo con dirección IP: 192.168.56.136 como servidor “Standby”. En la descripción del “Tnsentry” encontrara la inclusión de ambos servidores. En el archivo “sqlnet.ora” la inclusión del parámetro “SQLNET.INBOUND_CONNECT_TIMEOUT”

Para mayor información del uso del parámetro “SQLNET.INBOUND_CONNECT_TIMEOUT”, colocamos acá la referencia textual de su descripción proveniente de la documentación oficial Oracle.
http://docs.oracle.com/cd/B28359_01/network.111/b28317/sqlnet.htm#CIHCCCHD

El objetivo principal del articulo y de la técnica que estamos exponiendo es presentar una configuración en la que sea posible que el cliente pueda conectarse indistintamente a la base de datos primaria independientemente de que esta se encuentre en cualquiera de los servidores sin modificar los archivos del cliente para cuando ocurra alguna transición ocasionada por un “Switchover” o “Failover”.
En la figura tenemos como ejemplo la ejecución de una operación de “Failover”. Internamente en la base de datos de producción y por consiguiente de forma replicada en la base de datos “Standby”, tendremos un servicio que para el presente caso lleva por nombre “ADMAPP”. El mismo estará iniciado “started” solo en la base de datos primaria, en la base de datos “Standby” el mismo estará detenido. El control para lo mencionado lo establecernos a través de un disparador en evento “Startup on Database”. Tal como podrán visualizar el código es bastante sencillo, si el rol que ejecuta dicha base de datos en ese momento es de tipo “Primary” entonces se procederá a su inicio en caso contrario permanecerá detenido como es su condición por defecto al momento del inicio de la base de datos.


Ubiquémonos en el escenario en el cual ya se ha llevado a cabo una operación de “Swithover” o “Failover”. Como resultado de la misma la base de datos primaria transformo su rol a “Standby Database” y viceversa para la original “Standby Database”, la cual para el momento desempeñaría rol como base de datos primaria.
Para el caso descrito, los clientes podrán establecer conexión sin problema alguno bajo esta nueva configuración debido a que el servicio “ADMAPP” se encuentra iniciado en la base de datos primaria que se encuentra trabajando en el servidor ( 192.168.56.136 ). Analizando la configuración “tnsentry” descrita, observara que la misma soporta la conexión descrita.

Entonces de esta sencilla manera podemos establecer “Client Failover” para bases de datos “Standby”. Lo mostrado acá es solo el concepto principal. Hay información adicional que conocer con respecto a que pasaría con el funcionamiento del “Observer” en caso de estar configurado, como aplicar TAF y sus efectos.. etc .. todo ello lo abarcaremos en la próxima entrega.
Para concluir el presente artículo mostremos un ejemplo de “tnsentry” para soportar el modelo descrito para ambiente RAC. Tal como puede apreciarse, poseemos una entrada para una configuración RAC, para dicho caso seria la solución típica que conforma el primario ( Base de datos de producción en RAC ) y el lado “Standby” configurado para el presente caso con un servidor con base de datos “Single Instance”. Descripción de la figura:
*  “LOAD_BALANCE” & “FAILOVER” para los 2 elementos de la lista ( Configuración RAC & “Single Instance” )
* Como es de forma natural y habitual, “LOAD_BALANCE” para la configuración interna de la solución RAC.

Estimados lectores hemos llegado al final de esta entrega, esperando que el presente artículo sea de utilidad. Nos despedimos hasta la próxima entrega.
Saludos!

PURGE AUDITORIA 11G - 12C

Como decíamos al principio, vamos ha configurar la base de datos para que se borren los registros anteriores a 100 días.

Lo primero que tendremos que hacer es inicializar el paquete con  DBMS_AUDIT_MGMT.init_cleanup

 En nuestro caso lo lanzaremos sobre AUDIT_TRAIL_AUD_STD Ya que lo que queremos limpiar son los registros de las tablas de auditoria de la base de datos, si quisiéramos limpiar otro (por ejemplo los del S.O seguiríamos la tabla Audit Trail Types)
BEGIN
 DBMS_AUDIT_MGMT.init_cleanup(
 audit_trail_type => DBMS_AUDIT_MGMT.AUDIT_TRAIL_AUD_STD,
 default_cleanup_interval => 24 /* horas*/);
END;
Tras esto, con la propiedad SET_LAST_ARCHIVE_TIMESTAMP indicamos cual es la fecha del ultimo registro que queremos guardar.(en nuestro caso borraremos todo lo anterior a 100 días)
BEGIN
  DBMS_AUDIT_MGMT.SET_LAST_ARCHIVE_TIMESTAMP(
    audit_trail_type  => DBMS_AUDIT_MGMT.AUDIT_TRAIL_AUD_STD,
    last_archive_time => SYSTIMESTAMP-100 /*100 días*/);
END;
-- Set the Maximum age of XML audit files to 10 days.
BEGIN
  DBMS_AUDIT_MGMT.set_audit_trail_property(
    audit_trail_type           => DBMS_AUDIT_MGMT.AUDIT_TRAIL_XML,
    audit_trail_property       => DBMS_AUDIT_MGMT.OS_FILE_MAX_AGE,
    audit_trail_property_value => 10);
END;
/
Antes de ejecutar el trabajo, vamos a ver cual es el registro más antiguo:
SQL> select min(ntimestamp#) from sys.aud$;
-------------------------------------------
17/10/13 00:00:50,119000
Ejecutamos el purgado con la llamada
BEGIN
  DBMS_AUDIT_MGMT.CLEAN_AUDIT_TRAIL(
   audit_trail_type=> DBMS_AUDIT_MGMT.AUDIT_TRAIL_AUD_STD,
   use_last_arch_timestamp => TRUE);
END;
Tras ejecutar esto, el último registro debería de corresponderse con la fecha SYSDATE-100.
Si lo comprobamos tendremos que
SQL> select to_date(SYSTIMESTAMP-100) from dual 
--------
11/11/13
SQL> select min(ntimestamp#) from sys.aud$;
------------------------------------------
11/11/13 16:46:08,889000
Con lo que, efectivamente, habremos borrado todos los registros anteriores a 100 días.
A partir de ahora, podemos, o bien llevar a cabo los borrados de manera puntual con la llamada anterior, o planificarlos con en un job de purgado con la llamada
BEGIN
  DBMS_AUDIT_MGMT.CREATE_PURGE_JOB(
    audit_trail_type  => DBMS_AUDIT_MGMT.AUDIT_TRAIL_AUD_STD,
    audit_trail_purge_interval => 24 /* horas */,  
    audit_trail_purge_name => 'PURGADO_DE_TABLAS_AUDITORIA',
    use_last_arch_timestamp=> TRUE);
END;

Generando reportes AWR, ASH y ADDM

Generando reportes AWR, ASH y ADDM
En algún momento durante el monitoreo de nuestra base de datos Oracle será necesario obtener información detallada en reportes, estos podrían ser los de AWR, AHR y/o ADDM. Este post se enfocará en realizar las mismas utilizando scripts, una manera alternativa a lo que nos ofrece con la interfaz gráfica de Enterprise Manager. A continuación se detalla los pasos para obtener los reportes.

A) Reporte AWR (awrrpt.sql)
El utilitario de informes AWR proporciona una visión general del rendimiento de bases de datos en un determinado tiempo. En esencia, calcula la variación de la actividad de la base de datos en el intervalo de tiempo elegido. el script "awrrpt.sql" se encuentra en el directorio $ORACLE_HOME/RDBMS/admin.
La salida del archivo es ubicada en el directorio actual. Para una mejor comprensión de dicho informe seleccionar el formato HTML.

1. Ingresamos al directorio donde se generará el Informe AWR.
bash-3.2$ cd /u01/informes/
bash-3.2$ pwd
/u01/informes
bash-3.2$ ls
bash-3.2$
2 Nos conectamos vía sqlplus con usuario de provilegios de DBA.
bash-3.2$ sqlplus pticona

SQL*Plus: Release 11.2.0.3.0 Production on Sun Jun 22 23:58:15 2014

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

Enter password:

Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
With the Partitioning, Automatic Storage Management, OLAP, Data Mining
and Real Application Testing options

SQL>
3. Ejecutamos awrrpt.sql y nos aparecerá los datos actuales de la instancia.
SQL> @$ORACLE_HOME/rdbms/admin/awrrpt.sql

Current Instance
~~~~~~~~~~~~~~~~

   DB Id    DB Name      Inst Num Instance
----------- ------------ -------- ------------
  798387748 PRMY                1 prmy
3.1. Elegimos la opción para que el informe se genere en formato "html".
Specify the Report Type
~~~~~~~~~~~~~~~~~~~~~~~
Would you like an HTML report, or a plain text report?
Enter 'html' for an HTML report, or 'text' for plain text
Defaults to 'html'
Enter value for report_type:html

Type Specified:  html


Instances in this Workload Repository schema
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

   DB Id     Inst Num DB Name      Instance     Host
------------ -------- ------------ ------------ ------------
* 798387748         1 PRMY         prmy         primario

Using  798387748 for database Id
Using          1 for instance number

3.2. Para encontrar todos los AWR de la base de datos solo damos enter sin escribir nada.
Specify the number of days of snapshots to choose from
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Entering the number of days (n) will result in the most recent
(n) days of snapshots being listed.  Pressing  without
specifying a number lists all completed snapshots.

Enter value for num_days:

Listing all Completed Snapshots

                                                        Snap
Instance     DB Name        Snap Id    Snap Started    Level
------------ ------------ --------- ------------------ -----
prmy         PRMY                 1 18 Jun 2014 01:30      1
                                  2 18 Jun 2014 11:13      1
                                  3 18 Jun 2014 12:00      1
                                  4 22 Jun 2014 15:04      1
                                  5 22 Jun 2014 16:00      1
                                  6 22 Jun 2014 17:00      1
                                  7 22 Jun 2014 18:00      1
                                  8 22 Jun 2014 19:00      1
                                  9 22 Jun 2014 20:00      1
                                 10 22 Jun 2014 21:00      1
                                 11 22 Jun 2014 22:00      1
                                 12 22 Jun 2014 23:00      1
                                 13 23 Jun 2014 00:01      1
3.3. Con el listado desplegado, elegimos el intervalo de tiempo.
Specify the Begin and End Snapshot Ids
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter value for begin_snap: 10
Begin Snapshot Id specified: 10

Enter value for end_snap: 11
End   Snapshot Id specified: 11
3.4. Asignamos el nombre para el reporte.
Specify the Report Name
~~~~~~~~~~~~~~~~~~~~~~~
The default report file name is awrrpt_1_10_11.html.  To use this name,
press  to continue, otherwise enter an alternative.

Enter value for report_name: reporte_awr.html
.
.
Report written to reporte_awr.html
3.5. Salimos de sqlplus.
SQL> exit
Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
With the Partitioning, Automatic Storage Management, OLAP, Data Mining
and Real Application Testing options
bash-3.2$
4 Finalmente verificamos el archivo creado.
bash-3.2$ pwd
/u01/informes
bash-3.2$ ls
reporte_awr.html
bash-3.2$
5 Para realizar una comparativa de reportes AWR, utilizar el siguiente script.
SQL> @$ORACLE_HOME/rdbms/admin/awrddrpt.sql
B) Reporte ASH (ashrpt.sql)
El reporte ASH es útil para determinar la cantidad de sesiones activas, lo que estaban haciendo, y que sentencias SQL son las más activas durante el período de tiempo seleccionado. Especialmente es muy útil para el análisis de problemas de rendimiento transitoria. El script "ashrpt.sql" se encuentra en el directorio $ORACLE_HOME/RDBMS/admin.
La salida del archivo es ubicada en el directorio actual. Para una mejor comprension de dicho informe seleccionar el formato HTML. 

1. Ingresamos al directorio donde se generará el Informe ASH.
bash-3.2$ cd /u01/informes/
bash-3.2$ pwd
/u01/informes
bash-3.2$ ls
bash-3.2$
2 Nos conectamos vía sqlplus con usuario de provilegios de DBA.
bash-3.2$ sqlplus pticona

SQL*Plus: Release 11.2.0.3.0 Production on Sun Jun 22 23:58:15 2014

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

Enter password:

Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
With the Partitioning, Automatic Storage Management, OLAP, Data Mining
and Real Application Testing options

SQL>
3. Ejecutamos ashrpt.sql y nos aparecerá los datos actuales de la instancia.
SQL> @$ORACLE_HOME/rdbms/admin/ashrpt.sql

Current Instance
~~~~~~~~~~~~~~~~

   DB Id    DB Name      Inst Num Instance
----------- ------------ -------- ------------
  798387748 PRMY                1 prmy
3.1. Elegimos la opción para que el informe se genere en formato "html".
Specify the Report Type
~~~~~~~~~~~~~~~~~~~~~~~
Enter 'html' for an HTML report, or 'text' for plain text
Defaults to 'html'
Enter value for report_type: html

Type Specified:  html

Instances in this Workload Repository schema
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

   DB Id     Inst Num DB Name      Instance     Host
------------ -------- ------------ ------------ ------------
* 798387748         1 PRMY         prmy         primario

Defaults to current database

Using database id: 798387748

Enter instance numbers. Enter 'ALL' for all instances in a
RAC cluster or explicitly specify list of instances (e.g., 1,2,3).
Defaults to current instance.

Using instance number(s): 1

3.2. Ingresamos la hora de inicio y el intervalo de tiempo de duracion para el reporte ASH.
ASH Samples in this Workload Repository schema
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Oldest ASH sample available:  18-Jun-14 01:19:24   [   7150 mins in the past]
Latest ASH sample available:  23-Jun-14 00:29:06   [      0 mins in the past]


Specify the timeframe to generate the ASH report
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter begin time for report:

--    Valid input formats:
--      To specify absolute begin time:
--        [MM/DD[/YY]] HH24:MI[:SS]
--        Examples: 02/23/03 14:30:15
--                  02/23 14:30:15
--                  14:30:15
--                  14:30
--      To specify relative begin time: (start with '-' sign)
--        -[HH24:]MI
--        Examples: -1:15  (SYSDATE - 1 Hr 15 Mins)
--                  -25    (SYSDATE - 25 Mins)

Defaults to -15 mins
Enter value for begin_time: 06/22/14 21:05
Report begin time specified: 06/22/14 21:05

Enter duration in minutes starting from begin time:
Defaults to SYSDATE - begin_time
Press Enter to analyze till current time
Enter value for duration: 60
Report duration specified:   60

Using 22-Jun-14 21:05:00 as report begin time
Using 22-Jun-14 22:05:00 as report end time
3.3. Asignamos el nombre para el reporte ASH.
Specify the Report Name
~~~~~~~~~~~~~~~~~~~~~~~
The default report file name is ashrpt_1_0622_2205.html.  To use this name,
press  to continue, otherwise enter an alternative.
Enter value for report_name: reporte_ash.html
.
.
Report written to reporte_ash.html
3.4. Salimos de sqlplus.
SQL> exit
Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
With the Partitioning, Automatic Storage Management, OLAP, Data Mining
and Real Application Testing options
bash-3.2$
4 Finalmente verificamos el archivo creado.
bash-3.2$ pwd
/u01/informes
bash-3.2$ ls
reporte_ash.html
bash-3.2$
C) Reporte ADDM (addmrpt.sql)
El utilitario de ADDM crea un informe con las conclusiones de rendimiento de base de datos. El script "addmrpt.sql" se encuentra en el directorio $ORACLE_HOME/RDBMS/admin. La salida del archivo se ubica en el directorio actual y es enformato de archivo de texto.
1. Ingresamos al directorio donde se generará el reporte ADDM.
bash-3.2$ cd /u01/informes/
bash-3.2$ pwd
/u01/informes
bash-3.2$ ls
bash-3.2$
2 Nos conectamos vía sqlplus con usuario de provilegios de DBA.
bash-3.2$ sqlplus pticona

SQL*Plus: Release 11.2.0.3.0 Production on Sun Jun 22 23:58:15 2014

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

Enter password:

Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
With the Partitioning, Automatic Storage Management, OLAP, Data Mining
and Real Application Testing options

SQL>
3. Ejecutamos addmrpt.sql y nos aparecerá los datos actuales de la instancia.
SQL> @$ORACLE_HOME/rdbms/admin/addmrpt.sql

Current Instance
~~~~~~~~~~~~~~~~

   DB Id    DB Name      Inst Num Instance
----------- ------------ -------- ------------
  798387748 PRMY                1 prmy


Instances in this Workload Repository schema
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

   DB Id     Inst Num DB Name      Instance     Host
------------ -------- ------------ ------------ ------------
* 798387748         1 PRMY         prmy         primario

Using  798387748 for database Id
Using          1 for instance number


Specify the number of days of snapshots to choose from
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Entering the number of days (n) will result in the most recent
(n) days of snapshots being listed.  Pressing  without
specifying a number lists all completed snapshots.



Listing the last 3 days of Completed Snapshots

                                                        Snap
Instance     DB Name        Snap Id    Snap Started    Level
------------ ------------ --------- ------------------ -----
prmy         PRMY                 4 22 Jun 2014 15:04      1
                                  5 22 Jun 2014 16:00      1
                                  6 22 Jun 2014 17:00      1
                                  7 22 Jun 2014 18:00      1
                                  8 22 Jun 2014 19:00      1
                                  9 22 Jun 2014 20:00      1
                                 10 22 Jun 2014 21:00      1
                                 11 22 Jun 2014 22:00      1
                                 12 22 Jun 2014 23:00      1
                                 13 23 Jun 2014 00:01      1
3.1. Elegimos el intervalo de snapshots para el reporte ADDM.
Specify the Begin and End Snapshot Ids
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter value for begin_snap: 10
Begin Snapshot Id specified: 10

Enter value for end_snap: 11
End   Snapshot Id specified: 11
3.2. Asignamos el nombre para el reporte.
Specify the Report Name
~~~~~~~~~~~~~~~~~~~~~~~
The default report file name is addmrpt_1_10_11.txt.  To use this name,
press  to continue, otherwise enter an alternative.

Enter value for report_name: reporte_addm.txt
.
.
.
The database's maintenance windows were active during 100% of the analysis
period.

End of Report
Report written to reporte_addm.txt
SQL>
3.3. Salimos de sqlplus.
SQL> exit
Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
With the Partitioning, Automatic Storage Management, OLAP, Data Mining
and Real Application Testing options
bash-3.2$
4 Finalmente verificamos el archivo creado.
bash-3.2$ pwd
/u01/informes
bash-3.2$ ls
reporte_addm.txt
bash-3.2$