viernes, 16 de mayo de 2008

Creating or replacing a synonym

Oracle/PLSQL: Synonyms



A synonym is an alternative name for objects such as tables, views, sequences, stored procedures, and other database objects.


Creating or replacing a synonym

The syntax for creating a synonym is:

create [or replace] [public] synonym [schema .] synonym_name
for [schema .] object_name [@ dblink];

The or replace phrase allows you to recreate the synonym (if it already exists) without having to issue a DROP synonym command.

The public phrase means that the synonym is a public synonym and is accessible to all users. Remember though that the user must first have the appropriate privileges to the object to use the synonym.

The schema phrase is the appropriate schema. If this phrase is omitted, Oracle assumes that you are referring to your own schema.

The object_name phrase is the name of the object for which you are creating the synonym. It can be one of the following:

tablepackage
viewmaterialized view
sequencejava class schema object
stored procedureuser-defined object
functionsynonym

For example:

create public synonym suppliers
for app.suppliers;

This first example demonstrates how to create a synonym called suppliers. Now, users of other schemas can reference the table called suppliers without having to prefix the table name with the schema named app. For example:

select * from suppliers;

If this synonym already existed and you wanted to redefine it, you could always use the or replace phrase as follows:

create or replace public synonym suppliers
for app.suppliers;


Dropping a synonym

It is also possible to drop a synonym. The syntax for dropping a synonym is:

drop [public] synonym [schema .] synonym_name [force];

The public phrase allows you to drop a public synonym. If you have specified public, then you don't specify a schema.

The force phrase will force Oracle to drop the synonym even if it has dependencies. It is probably not a good idea to use the force phrase as it can cause invalidation of Oracle objects.


For example:

drop public synonym suppliers;

This drop statement would drop the synonym called suppliers that we defined earlier.

miércoles, 14 de mayo de 2008

Re: Pregunta de Oracle (email!)

El día 14 de mayo de 2008 11:25, Federico <fede@mail.com> escribió:
Hola Martín, cómo estás? Me surgió una duda sobre Oracle y se me ocurrió molestarte a vos...de todos modos no es mucho.

Tengo una tabla de unos 9 millones de registros (que no está particionada en table spaces), y cuando quiero borrar una cantidad importante de registros el SQL Plus se queda colgado, supongo que en algún momento da un timeout y luego se pone a hacer el rollback del que me contabas el otro día. Te parece que hacer un delete con un rownum pueda funcionar? o puedo llegar a romper algo?

mil gracias,

un abrazo,

Fede




El día 14 de mayo de 2008 23:16, Martin <martin@mail.com> escribió:


Romper no... a lo sumo va a seguir sin responder.

Pueden ocurrir muchas cosas... Se me ocurren otras alternativas pero no te sabria decir cual es la que te conviene mas...

¿Cuantos registros de los 9 millones tenes que borrar? ¿Son muchos mas que los que dejas? ¿Los borras con algun criterio o estas borrando los primeros N millones (la alternativa donde te serviria el ROWNUM)?

Al ser millones de reg la cosa se pone mas complicada...

Puede que esten mal dimensionados los parametros de la base, que los redo o el undo sean chicos para una transaccion tan grande (Oracle se asegura grabando en los redo y undo logs que de caerse la base pueda mantener la atomicidad del DELETE)...

Si la tabla estuviera particionada podrias truncar una particion (una particion no un tablespace, una tabla siempre esta contenida dentro de un unico tablespace). Aunque tendrias que tener cuidado que no tenga indices globales que se invaliden, si los hubiera tenes que hacer el truncate de la particion con la opcion rebuild online...

Ahora la pregunta es tienen pensado particionarla? ¿Pueden particionarla y despues hacer el truncate de la particion? (para particionarla hay que recrear el objeto).

Si no fueran muchos registros te conviene hacer un pequeño PL-SQL que haga commits cada cierta cantidad de registros (ojo porque le estas quitando atomicidad a la operacion y deja de hacerse o deshacerse por completo, solo x bloque PL que definas)...

Podes usar una tabla temporal en modo nologging asi no te caga llenando redo y undo y mandar los registros que queres conservar a la temporal y dropear la original para despues renombrar la temporal a la original... vas a tener que hacer otras cosas en medio como deshabilitar constraints si los hubiera... fijarte que el "manoseo" no haga que te exploten los tablespaces por el espacio que va a ocupar la tabla temporal (si no es un gran porcentaje el que borras pensa que seria como duplicar la tabla)...

No se si escuchaste de una instruccion BULK INSERT (o BULK COLLECT) que son para cargas masivas de datos, tenes una similar para borrar masivamente (que jamás la usé pero imagino que te puede ser de suma utilidad) que se llama...

chan ... chan... jajajaja. BULK DELETE como a esta altura ya te imaginaras por analogia con el anterior.

Aca va un ejemplo que encontre en la WEB:

DECLARE
TYPE num_nt IS TABLE OF VARCHAR2(20);
TYPE descr_nt IS TABLE OF VARCHAR2(20);

nt_x_nums num_nt := num_nt();
nt_a_descrs descr_nt := descr_nt();

v_cnt_sqlrow NUMBER := 0;
SELECT id BULK COLLECT
INTO nt_x_nums
FROM a;

v_cnt_sqlrow :=SQL%ROWCOUNT;
-- DBMS_OUTPUT.PUT_LINE(v_cnt_sqlrow);

FORALL i IN nt_x_nums.FIRST..nt_x_nums.LAST
DELETE FROM t
WHERE id= nt_x_nums(i)

RETURNING id BULK COLLECT INTO nt_a_descrs
Espero que te haya servido!

Cualquier cosa preguntame!

Slds,

Martin

PD: Aca va el link de la pagina de donde saqué el ejemplo.

http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:5033906925164.


Tuning & Performance Tips

Algunas paginas utiles con tips para mejorar performance en Oracle:


http://download-west.oracle.com/docs/cd/B10500_01/appdev.920/a96624/12_tune.htm
http://www.devshed.com/c/a/Oracle/Tuning-PLSQL-Code/
http://www.stanford.edu/dept/itss/docs/oracle/10g/appdev.101/b10807/12_tune.htm

CREATE DATABASE LINK / DROP DATABASE LINK

CREATE DATABASE LINK command


PURPOSE: To create a database link. A database link is an object in the local database that allows you to access objects on a remote database or to mount a secondary database in read-only mode. The remote database can be either an Oracle or a non-Oracle database.

SYNTAX:

CREATE [PUBLIC] DATABASE LINK dblink [CONNECT TO user IDENTIFIED BY password] [USING 'connect_string']

where:
  • PUBLIC creates a public database link available to all users. If you omit this option, the database link is private and is available only to you. dblink is the complete or partial name of the database link. For guidelines for naming database links, see the section Referring to Objects in Remote Databases.
  • CONNECT TO user IDENTIFIED BY password is the username and password used to connect to the remote database. If you omit this clause, the database link uses the username and password of each user who uses the database link.
  • USING specifies either: * the database specification of a remote database * the specification of a secondary database for a read-only mount. For information on specifying remote databases, see the SQL*Net User's Guide for your specific SQL*Net protocol. Read-only mounts are only available in Trusted Oracle and can only be specified for public database links.

PREREQUISITES: To create a private database link, you must have CREATE DATABASE LINK system privilege. To create a public database link, you must have CREATE PUBLIC DATABASE LINK system privilege. Also, you must have CREATE SESSION privilege on a remote database. SQL*Net must be installed on both the local and remote databases.

Drop a Database Link.

Syntax:

   DROP [PUBLIC] DATABASE LINK link_name
Restrictions: You cannot drop a database link in another user's schema and you must specify PUBLIC to drop a PUBLIC database link

Sources:
http://www.ss64.com/ora/link_d.html
http://www-eleves-isia.cma.fr/documentation/OracleDoc/CREATE-DATABASE-LINK.html

Refrescar un Snapshot MANUALMENTE

The 'REFRESH' stored procedure of the DBMS_SNAPSHOT package can be used
to manually refresh a snapshot. The syntax is:

EXECUTE dbms_snapshot.refresh (' [ schema.] name ' [, 'refresh_option'])

For example, to do a FAST refresh of the EMP snapshot:

EXECUTE dbms_snapshot.refresh ('emp', ' f ' ) ;

Refresh Options: 'F' or 'f' = FAST refresh
'C' or 'c' = COMPLETE refresh
'?' = DEFAULT refresh option

martes, 13 de mayo de 2008

Startup

Starting your Oracle Database

One of the most common jobs of the database administrator is to startup or shutdown the Oracle database. Typically we hope that database shutdowns will be infrequent for a number of reasons:

* Inconvenience to the user community.

* Anytime you cycle the database, there is a risk that it will not restart.

* It flushes the Oracle memory areas, such as the database buffer cache.

Performance on a restarted database will generally be slow until the database memory areas are "warmed" up.

Why would you shutdown your database? Some reasons include database maintenance:

* Applying a patch or an upgrade.

* Allow for certain types of application maintenance.

* Performing a cold (offline) backup of your database. (We recommend hot backups that allow you to avoid shutting down your database)

* An existing bug in your Oracle software requires you to restart the database on a regular basis.

When the time comes to "bounce" the database (using the shutdown and startup commands), you will use SQL*Plus to issue these commands. Let's look at each of these commands in more detail.

The Oracle Startup Command

You start the Oracle database with the startup command. You must first be logged into an account that has sysdba or sysoper privileges such as the SYS account (we discussed connecting as SYSDBA earlier in this book). Here then is an example of a DBA connecting to his database and starting the instance:

C:\Documents and Settings\Robert>set oracle_sid=booktst
C:\Documents and Settings\Robert>sqlplus "sys as sysdba"
SQL*Plus: Release 10.1.0.2.0 - Production on Mon Feb 21 12:35:48
Enter password: xxxx
Connected to an idle instance.
SQL> startup
ORACLE instance started.
Total System Global Area 251658240 bytes
Fixed Size 788368 bytes
Variable Size 145750128 bytes
Database Buffers 104857600 bytes
Redo Buffers 262144 bytes
Database mounted.
Database opened.

In this example from a Windows XP server, we set the ORACLE_SID to the name of the database and we log into SQL*Plus using the "sys as sysdba" login. This gives us the privileges we need to be able to startup the database. Finally, after we enter our password, we issue the startup command to startup the database. Oracle displays its progress as it opens the database, and then returns us to the SQL*Plus prompt once the startup has been completed.

When Oracle is trying to open your database, it goes through three distinct stages, and each of these is listed in the startup output listed previously. These stages are:

* Startup (nomount)

* Mount

* Open

Let's look at these stages in a bit more detail.

The Startup (nomount) Stage

When you issue the startup command, the first thing the database will do is enter the nomount stage. During the nomount stage, Oracle first opens and reads the initialization parameter file (init.ora) to see how the database is configured. For example, the sizes of all of the memory areas in Oracle are defined within the parameter file.

After the parameter file is accessed, the memory areas associated with the database instance are allocated. Also, during the nomount stage, the Oracle background processes are started. Together, we call these processes and the associated allocated memory the Oracle instance. Once the instance has started successfully, the database is considered to be in the nomount stage. If you issue the startup command, then Oracle will automatically move onto the next stage of the startup, the mount stage.

Starting the Oracle Instance (Nomount Stage)

There are some types of Oracle recovery operations that require the database to be in nomount stage. When this is the case, you need to issue a special startup command: startup nomount, as seen in this example:

SQL> startup nomount

The Mount Stage

When the startup command enters the mount stage, it opens and reads the control file. The control file is a binary file that tracks important database information, such as the location of the database datafiles.

In the mount stage, Oracle determines the location of the datafiles, but does not yet open them. Once the datafile locations have been identified, the database is ready to be opened.

Mounting the Database

Some forms of recovery require that the database be opened in mount stage. To put the database in mount stage, use the startup mount command as seen here:

SQL> startup mount

If you have already started the database instance with the startup nomount command, you might change it from the nomount to mount startup stage using the alter database command:

SQL> alter database mount;

The Open Oracle startup Stage

The last startup step for an Oracle database is the open stage. When Oracle opens the database, it accesses all of the datafiles associated with the database. Once it has accessed the database datafiles, Oracle makes sure that all of the database datafiles are consistent.

Opening the Oracle Database

To open the database, you can just use the startup command as seen in this example

SQL> startup

If the database is mounted, you can open it with the alter database open command as seen in this example:

SQL> alter database open;

Opening the Database in Restricted Mode

You can also start the database in restricted mode. Restricted mode will only allow users with special privileges (we will discuss user privileges in a later chapter) to access the database (typically DBA's), even though the database is technically open. We use the startup restrict command to open the database in restricted mode as seen in this example.

SQL> startup restrict

You can take the database in and out of restricted mode with the alter database command as seen in this example:

-- Put the database in restricted session mode.

SQL> alter database enable restricted session;

-- Take the database out of restricted session mode.

SQL> alter database disable restricted session;

Note: Any users connected to the Oracle instance when going into restricted mode will remain connected; they must be manually disconnected from the database by exiting gracefully or by the DBA with the "alter system kill session" command.

Problems during Oracle Startup

The typical DBA life is like that of an airline pilot, "Long moments of boredom followed by small moments of sheer terror", and one place for sheer terror is an error during a database startup.

¿Soy un DBA? - El catálogo del sistema en ORACLE

¿Cómo saber si estoy dentro del ROL de DBAs?

Hace un par de días tuve que verificar si mi nuevo usuario tenía permisos de DBA sobre algunas de las bases de datos. Ahora ¿Cómo podría hacer esta verificación?

La respuesta es fácil, necesito consultar las tablas con prefijo 'DBA_'. Si tengo granteado el acceso a las mismas entonces tengo acceso al catalogo del sistema y por ende los derechos de un DBA. Estas no son las únicas tablas que componen el catalogo, pero para el ejemplo y para descubrir si somos o no DBAs son más que suficientes.

El Catálogo de Oracle

Oracle cuenta con una serie de tabla y vistas que conforman una estructura denominada catálogo. La principal función del catálogo de Oracle es almacenar toda la información de la estructura lógica y física de la base de datos, desde los objetos existentes, la situación de los datafiles, la configuración de los usuarios, etc.

El catálogo sigue un estándar de nomenclatura para que su memorización sea más fácil:

Prefijo/Descripción
DBA_ Objetos con información de administrador. Sólo accesibles por con permisos DBA.
  • USER_ Objetos con información propia del usuario al que estamos conectado. Accesible desde todos los usuarios. Proporcionan menos información que los objetos DBA_
  • ALL_ Objetos con información de todos los objetos en base de datos.
  • V_$ ó V$ Vistas dinámicas sobre datos de rendimiento
  • Existe un pseudo-usuario llamado PUBLIC el cual tiene acceso a todas las tablas del catálogo público. Si se quiere que todos los usuarios tengan algún tipo de acceso a un objeto, debe darse ese privilegio a PUBLIC y todo el mundo dispondrá de los permisos correspondientes.

    El catálogo público son aquellas tablas (USER_ y ALL_) que son accesibles por todos los usuarios. Normalmente dan información sobre los objetos creados en la base de datos.

    El catálogo de sistema (DBA_ y V_$) es accesible sólo desde usuarios DBA y contiene tanto información de objetos en base de datos, como información específica de la base de datos en sí (versión, parámetros, procesos ejecutándose…)

    Ciertos datos del catálogo de Oracle están continuamente actualizados, como por ejemplo las columnas de una tabla o las vistas dinámicas (V$). De hecho, en las vistas dinámicas, sus datos no se almacenan en disco, sino que son tablas sobre datos contenidos en la memoria del servidor, por lo que almacenan datos actualizados en tiempo real. Algunas de las principales son:

    • V$DB_OBJECT_CACHE: contiene información sobre los objetos que están en el caché del SGA.
    • V$FILESTAT: contiene el total de lecturas y escrituras físicas sobre un data file de la base de datos.
    • V$ROLLSTAT: contienen información acerca de los segmentos de rollback.

    Sin embargo hay otros datos que no pueden actualizarse en tiempo real porque penalizarían mucho el rendimiento general de la base de datos, como por ejemplo el número de registros de una tabla, el tamaño de los objetos, etc. Para actualizar el catálogo de este tipo de datos es necesario ejecutar una sentencia especial que se encarga de volcar la información recopilada al catálogo:

    ANALYZE [TABLEINDEX] nombre [COMPUTEESTIMATEDELETE] STATISTICS;

    La cláusula COMPUTE hace un cálculo exacto de la estadísticas (tarda más en realizarse en ANALYZE), la cláusula ESTIMATE hace una estimación partiendo del anterior valor calculado y de un posible factor de variación y la cláusula DELETE borra las anteriores estadísticas.

    viernes, 9 de mayo de 2008

    Mi primer Script

    Hoy escribí mi primer script para el nuevo laburo, me conecté a las bases de datos cambié passwords y empece a "producir" casi 14 días después de haber venido por primera vez como empleado.
    SELECT FS.tablespace_name AS TSNAME,
    (DF.total_space - FS.free_space) AS MB_USED,
    FS.free_space AS MB_FREE,
    DF.total_space AS MB_TOTAL,
    to_char(round(100 * (FS.free_space / DF.total_space))) '%' AS PCT_FREE
    FROM
    (SELECT tablespace_name,
    round(sum(bytes) / 1048576) "TOTAL_SPACE" -- Puede cambiarse 1048576 x POWER(1024,2) --MB
    FROM dba_data_files
    GROUP BY tablespace_name) DF,
    (SELECT tablespace_name,
    round(sum(bytes) / 1048576) "FREE_SPACE"
    FROM dba_free_space
    GROUP BY tablespace_name) FS
    WHERE DF.tablespace_name = FS.tablespace_name
    ORDER BY round(100 * (FS.free_space / DF.total_space)) DESC;

    ALTER TABLESPACE ADD DATAFILE '/var/adm/SeOS/oracle/DataFileName.DBF' SIZE 5.5G;

    /

    También cometí mi primer error!
    Fue no considerar en mi script que los datafiles tienen una "property" de autoextend y eso hace que a pesar de que el tablespace este al 99% ocupado, no se lo categoricoe como un hecho critico ya que todavia es posible que el datafile tenga mucho espacio para "auto-extenderse". En todo caso deberia revisar que todavia que de espacio para extenderse.

    lunes, 28 de abril de 2008

    Configurar DNS en SUN SOLARIS 10

    Se me presento el problema que despues de instalar solaris 10 en mi VMWARE no podia navegar por internet. No estar rolviendo nombres porque por IPs si podia acceder a las paginas.
    ¿Cómo solucionarlo?
    Veamos el contenido del siguiente articulo:
    1) You need to create or edit the file /etc/resolv.conf

    # cat resolv.conf
    domainname corp.petrobras.biz
    nameserver 10.26.42.1
    nameserver 10.2.56.33
    nameserver 10.2.56.34
    search corp.petrobras.biz,engenharia.petrobras.com.br,petrobras.com.br
    #
    Where :
    a) domainname => name of domain
    b) nameserver => you can put until 3 DNS servers (IP)
    c) search (optional) => used to complete a host name, when you use just the first name to resolve hosts.
    Ex: When you put test, the system will search test.corp.petrobras.biz, test.engenharia.petrobras.com.br and so on.

    2) You must edit the file /etc/nsswitch.conf and include the word "dns" after "files" in the line shown below . So the system will resolve host using the file /etc/hosts and /etc/resolv.conf in this order.

    ...
    hosts: files dns
    ...

    Good luck

    domingo, 20 de abril de 2008

    TKPROF y Tracefile

    Es necesario usar dos parametros de la base de datos, para realizar el trace de las sesiones:

    • TIMED_STATISTICS : que debe ser TRUE para usar estadisticas.

    • USER_DUMP_DEST : donde se establece el directorio donde el server escribirá los tracefiles.
    Existe un parámetro relacionado a este último:
    • MAX_DUMP_FILE_SIZE : que permite establecer el tamaño máximo del tracefile, lo valores válidos para este parámetro son UNLIMITED, o un número seguido de una M o K para establecer el tamaño en Megabytes o KBytes como tamaño máximo a ocupar. De solo tener un número (sin la letra M o K) se considera que está especificándose el número máximo de bloques del SO que el archivo puede ocupar.


    ¿Cómo habilitarlo?



    Puede habilitarse de las siguientes maneras:

    1. SQL*Plus: SQL> alter session set sql_trace true;

    2. PL/SQL: dbms_session.set_sql_trace(TRUE);

    3. DBA: SQL> execute sys.dbms_system.set_sql_trace_in_session(sid,serial#,TRUE); donde sid y serial# provienen de la consulta Select username, sid, serial#, machine from v$session;

    4. PRO*C: EXEC SQL ALTER SESSION SET SQL_TRACE TRUE;


    ¿Cómo leo los tracefiles?



    Usando TKPROF puedo leer los tracefiles generando a partir de ellos un archivo de texto con el detalle. La sintaxis del comando es la siguiente



    TKPROF tracefile exportfile [explain=username/password] [table= …] [print= ] [insert= ] [sys= ] [record=..] [sort= ]



    Y un ejemplo,

    tkprof ora_12345.trc output.txt explain=scott/tiger

    Fuentes:

    martes, 15 de abril de 2008

    Aplicaciones J2EE - iSQLPlus

    He instalado el dbms Oracle 11g en la maquina virtual y estas son las direcciones desde las que se puede acceder al iSqlPlus.

    Se han desplegado las siguientes aplicaciones J2EE y se puede acceder a ellas en las siguientes direcciones URL.

    URL de iSQL*Plus:
    http://VMWARE-ORACLE:5560/isqlplus

    URL de DBA de iSQL*Plus:
    http://VMWARE-ORACLE:5560/isqlplus/dba

    URL Enterprise Manager 10g Database Control

    lunes, 14 de abril de 2008

    EXCELENTE BLOG con las tareas de un DBA

    http://delfinonunez.wordpress.com/page/4/


    Monitoreo de espacio en tablespace


    20 Julio, 2006 by delfinonunez

    Una de las tareas de un DBA es monitorear el espacio de la base de datos, debido a que esto consume mucho tiempo cuando se tienen varias DB’s es bueno automatizar tareas repetitivas y tediosas. Una manera de realizar la automatización del monitoreo de DB’s en UNIX es por medio del crontab, el siguiente es un ejemplo de como usar el crontab para monitorear los tablespaces.



    • Los siguientes scripts permiten obtener el espacio utilizado y libre de los tablespaces, uno lo obtiene en base el porcentaje libre de espacio y el otro obtiene el espacio en base a los MB libres. Estos scripts reciben dos parametros: &1 .- es el directorio y archivo donde se va a crear el reporte(spool) y &2 que es el limite ya sea porcentaje (99) o Mb(99999).


    tablespace_size_pct.sql



    SET line 132
    SET pages 50
    SET pause OFF
    SET feedback OFF
    SET echo OFF
    SET verify OFF

    COLUMN c1 heading "Tablespace|Name"
    COLUMN c2 heading "File|Count"
    COLUMN c3 heading "Allocated|in MB"
    COLUMN c4 heading "Used|in MB"
    COLUMN c5 heading "%|free" format 99.99
    COLUMN c6 heading "Free|in MB"
    COLUMN c7 heading "%|used" format 99.99

    spool &1;

    SELECT c1,ROUND(c3,2) c3,ROUND(c4,2) c4,ROUND(c6,2) c6,ROUND(c7,2) c7,ROUND(c5,2) c5,c2
    FROM(
    SELECT NVL (b.tablespace_name, NVL (a.tablespace_name, 'UNKOWN')) c1,
    mbytes_alloc c3, mbytes_alloc - NVL (mbytes_free, 0) c4,
    NVL (mbytes_free, 0) c6,
    ((mbytes_alloc - NVL (mbytes_free, 0)) / mbytes_alloc) * 100 c7,
    100
    - (((mbytes_alloc - NVL (mbytes_free, 0)) / mbytes_alloc) * 100) c5,
    b.files c2
    FROM (SELECT SUM (BYTES) / 1024 / 1024 mbytes_free, tablespace_name
    FROM SYS.dba_free_space
    GROUP BY tablespace_name) a,
    (SELECT SUM (BYTES) / 1024 / 1024 mbytes_alloc, tablespace_name,
    COUNT (file_name) files
    FROM SYS.dba_data_files
    GROUP BY tablespace_name) b
    WHERE a.tablespace_name(+) = b.tablespace_name
    UNION ALL
    SELECT f.tablespace_name,
    SUM (ROUND ((f.bytes_free + f.bytes_used) / 1024 / 1024, 2)
    ) "total MB",
    SUM (ROUND (NVL (p.bytes_used, 0) / 1024 / 1024, 2)) "Used MB",
    SUM (ROUND ( ((f.bytes_free + f.bytes_used) - NVL (p.bytes_used, 0)
    )
    / 1024
    / 1024,
    2
    )
    ) "Free MB",
    (SUM (ROUND (NVL (p.bytes_used, 0) / 1024 / 1024, 2)) * 100)
    / (SUM (ROUND ((f.bytes_free + f.bytes_used) / 1024 / 1024, 2))),
    100
    - (SUM (ROUND (NVL (p.bytes_used, 0) / 1024 / 1024, 2)) * 100)
    / (SUM (ROUND ((f.bytes_free + f.bytes_used) / 1024 / 1024, 2))),
    COUNT (d.file_name)
    FROM SYS.v_$temp_space_header f,
    dba_temp_files d,
    SYS.v_$temp_extent_pool p
    WHERE f.tablespace_name(+) = d.tablespace_name AND f.file_id(+) = d.file_id
    AND p.file_id(+) = d.file_id
    GROUP BY f.tablespace_name)
    WHERE C1 NOT IN('USERS')
    AND C7 >= &2
    ORDER BY c6 ASC;

    spool off;
    exit;

    tablespace_size_spc.sql



    SET line 132
    SET pages 50
    SET pause OFF
    SET feedback OFF
    SET echo OFF
    SET verify OFF

    COLUMN c1 heading "Tablespace|Name"
    COLUMN c2 heading "File|Count"
    COLUMN c3 heading "Allocated|in MB"
    COLUMN c4 heading "Used|in MB"
    COLUMN c5 heading "%|free" format 99.99
    COLUMN c6 heading "Free|in MB"
    COLUMN c7 heading "%|used" format 99.99

    spool &1;

    SELECT c1,ROUND(c3,2) c3,ROUND(c4,2) c4,ROUND(c6,2) c6,ROUND(c7,2) c7,ROUND(c5,2) c5,c2
    FROM(
    SELECT NVL (b.tablespace_name, NVL (a.tablespace_name, 'UNKOWN')) c1,
    mbytes_alloc c3, mbytes_alloc - NVL (mbytes_free, 0) c4,
    NVL (mbytes_free, 0) c6,
    ((mbytes_alloc - NVL (mbytes_free, 0)) / mbytes_alloc) * 100 c7,
    100
    - (((mbytes_alloc - NVL (mbytes_free, 0)) / mbytes_alloc) * 100) c5,
    b.files c2
    FROM (SELECT SUM (BYTES) / 1024 / 1024 mbytes_free, tablespace_name
    FROM SYS.dba_free_space
    GROUP BY tablespace_name) a,
    (SELECT SUM (BYTES) / 1024 / 1024 mbytes_alloc, tablespace_name,
    COUNT (file_name) files
    FROM SYS.dba_data_files
    GROUP BY tablespace_name) b
    WHERE a.tablespace_name(+) = b.tablespace_name
    UNION ALL
    SELECT f.tablespace_name,
    SUM (ROUND ((f.bytes_free + f.bytes_used) / 1024 / 1024, 2)
    ) "total MB",
    SUM (ROUND (NVL (p.bytes_used, 0) / 1024 / 1024, 2)) "Used MB",
    SUM (ROUND ( ((f.bytes_free + f.bytes_used) - NVL (p.bytes_used, 0)
    )
    / 1024
    / 1024,
    2
    )
    ) "Free MB",
    (SUM (ROUND (NVL (p.bytes_used, 0) / 1024 / 1024, 2)) * 100)
    / (SUM (ROUND ((f.bytes_free + f.bytes_used) / 1024 / 1024, 2))),
    100
    - (SUM (ROUND (NVL (p.bytes_used, 0) / 1024 / 1024, 2)) * 100)
    / (SUM (ROUND ((f.bytes_free + f.bytes_used) / 1024 / 1024, 2))),
    COUNT (d.file_name)
    FROM SYS.v_$temp_space_header f,
    dba_temp_files d,
    SYS.v_$temp_extent_pool p
    WHERE f.tablespace_name(+) = d.tablespace_name AND f.file_id(+) = d.file_id
    AND p.file_id(+) = d.file_id
    GROUP BY f.tablespace_name)
    WHERE C1 NOT IN('USERS')
    AND C6 <= &2
    ORDER BY c6 ASC;

    SPOOL OFF;
    exit;


    • Con el siguiente script podemos ejecutar los SQL scripts anteriores dependiendo los parametros que le enviemos. La forma de ejecutar el script es la siguiente:

      • Para reportar en base al espacio, despues del parametro -d debe seguir el nombre de la instancia (SID), despues del parametro -s sigue la cantidad minima que puede tener libre un tablespace:

        • tbs_monitor.ksh -d DEVELOPMENT -s 500

          Connected.
          Instance: DEVELOPMENT
          Tablespaces with usage < 500 MB.

          Tablespace Allocated Used Free % % File
          Name in MB in MB in MB used free Count
          ------------------------------ ---------- ---------- ---------- ------ ------ ----------
          SYSTEM 600 403.13 196.88 67.19 32.81 1
          IDX1 11741 11363 378 96.78 3.22 3




      • Para reportar en base al porcentaje, en lugar de utilizar el parametro -s se utiliza el parametro -p seguido del porcentaje maximo que puede tener un tablespace:

        • tbs_monitor.ksh -d DEVELOPMENT -p 80




      • Connected.
        Instance: DEVELOPMENT
        Tablespaces with usage >= 80%.

        Tablespace Allocated Used Free % % File
        Name in MB in MB in MB used free Count
        ------------------------------ ---------- ---------- ---------- ------ ------ ----------
        IDX1 11741 11363 378 96.78 3.22 3
        IDX2 3201 2696 505 84.22 15.78 2
        IDX5 18385 17394 991 94.61 5.39 3
        DATA02 13312 11520.13 1791.88 86.54 13.46 2
        DATA03 33797 31709.13 2087.88 93.82 6.18 4
        DATA01 56629 46606.38 10022.63 82.30 17.70 7





    Basic RMAN Backup

    Lets do a real simple backup using RMAN that writes it's output to a local file instead of the tape subsystem just to see how it works. In this case, we've got our database (SID: cuddle) up and running.

    [oracle@vixen oracle]$ echo $ORACLE_SID
    cuddle
    [oracle@vixen oracle]$ rman nocatalog target /
    Recovery Manager: Release 10.1.0.2.0 - 64bit Production
    Copyright (c) 1995, 2004, Oracle. All rights reserved.
    connected to target database: CUDDLE (DBID=251015092)
    using target database controlfile instead of recovery catalog
    RMAN> backup database;
    Starting backup at 02-NOV-04
    allocated channel: ORA_DISK_1
    channel ORA_DISK_1: sid=162 devtype=DISK
    channel ORA_DISK_1: starting full datafile backupset
    channel ORA_DISK_1: specifying datafile(s) in backupset
    input datafile fno=00001 name=/u02/oradata/cuddle/system01.dbf
    input datafile fno=00003 name=/u02/oradata/cuddle/sysaux01.dbf
    input datafile fno=00002 name=/u02/oradata/cuddle/undotbs01.dbf
    input datafile fno=00004 name=/u02/oradata/cuddle/users01.dbf
    channel ORA_DISK_1: starting piece 1 at 02-NOV-04
    channel ORA_DISK_1: finished piece 1 at 02-NOV-04
    piece handle=/u01/app/oracle/product/10.1.0/db_1/dbs/05g438u6_1_1 comment=NONE
    channel ORA_DISK_1: backup set complete, elapsed time: 00:01:45
    channel ORA_DISK_1: starting full datafile backupset
    channel ORA_DISK_1: specifying datafile(s) in backupset
    including current controlfile in backupset
    including current SPFILE in backupset
    channel ORA_DISK_1: starting piece 1 at 02-NOV-04
    channel ORA_DISK_1: finished piece 1 at 02-NOV-04
    piece handle=/u01/app/oracle/product/10.1.0/db_1/dbs/06g4391f_1_1 comment=NONE
    channel ORA_DISK_1: backup set complete, elapsed time: 00:00:03
    Finished backup at 02-NOV-04
    RMAN> quit
    Recovery Manager complete.
    [oracle@vixen oracle]$


    This is the most basic backup you can do with RMAN. We didn't tell RMAN how or where to backup the database, just simply to do it.
    The rman command is passed 2 arguments: the first "nocatalog" tells RMAN that we aren't using a recovery catalog database and the second "target /" is similar to a SQL*Plus connect statement, with information that RMAN requires to connect to the target database. The target is the database we wish to backup.
    Notice that RMAN returns some interesting information prior to giving us a prompt. It confirms that RMAN is connected to the target and lists that target. The DBID seen after the target database SID can be very important for later recoveries and it is recommend that you write it down somewhere for future use. RMAN then confirms that because we aren't using a recovery catalog to store backup metadata that it will instead store the data in the target databases control files.
    The RMAN command backup database; sends RMAN on its merry way backing up the database. Notice that we didn't tell it where or how to backup the data. By default the backup peices will be placed in the $ORACLE_HOME/dbs directory. This can get very messy since your system PFILES are in there too, and therefore we recommend that you don't use this location for your normal backups.
    Two backup peices were created. The first contains the datafiles holding the tablespaces including the undo tablespace. The second backup peice contains the current SPFILE and curent controlfile.
    Lets stop and think carefully for just a moment. Now, we've opted to use ARCHIVELOG mode which means we can do hot backups. However, we didn't want the hassle and administrative overhead of maintaining a recovery catalog. So here is the rub: recall that you need a PFILE/SPFILE to start an instance and you need the controlfile to point to all the files to be mounted. If the database were completely destroyed we would certainly need both the SPFILE and the Controlfile to access the backup peices made by RMAN.... but they are inside the backup we just made! Nice little loop of confusion huh? We'll talk about this later, but for now just keep it in mind.

    Fuentes:

    RMAN - ¿Qué es un SCN?

    An SCN in Oracle is nothing more than Oracle's clock: a chronology of changes.

    It is this chronology that affords Oracle the ability to perform recovery with exact precision.

    There are many types of events that trigger many types of checkpoints. But, for the sake of this discussion consider the global checkpoint triggered by a log switch. Upon this triggering event Oracle "notes" the current SCN. This is the SCN that will be written to the data file headers and their corresponding control file entries once Oracle has written ALL blocks up to and including that SCN to said files. At that point Oracle can assert with 100% certitude that the data file(s) are consistent with respect to that SCN - or simply that change-point in time. This doesn't mean all of the data written is committed or that there aren't blocks in the data files with higher SCNs by the time the checkpoint completes. It only means that Oracle can guarantee all changes, up to and including the checkpoint SCN, are written to the files.

    Fuentes:

    Using RMAN

    SysAdmin's have a definate love/hate relationship with RMAN. Many of us not so jokingly refer to it as the "Recovery Mangler". You love it because its fairly simple and is the only sure-fire way to perform online backups. You hate it because it's often cryptic, and either works or doesn't. Because RMAN couples closely with a backup infastructure there is alot of finger pointing when problems arise between "It's an RMAN issue!" and "No, it's a NetBackup issue!". RMAN causes DBAs and UNIX admins to get too close for comfort and niether generally understands the wholistic view of the interaction properly.

    So, why would a sysadmin like RMAN?

    • RMAN can perform online (hot) backups
    • RMAN can allow for partial or complete recovery
    • No fear of incomplete backups
    • DBA initiated backups and recovery without the interaction of the SA
    • Intigration with existing backup infistructure

    The problem with backing up Oracle using traditional methods is similar to the problems with backing up filesystems, unless you shutdown the database and perform a cold backup there is no way to know that all the transactions and changes have been written to datafiles. The SGA maintans a huge amount of data in active memory which can cause a problem. It's alittle like editing a configuration file on the system and then halting the system and wondering where your changes went. In order to ensure consistance of the database we need a hot backup method. If we restore a filesystem backup of the database that was taken while Oracle was running we run the risk of lossing database changes at best or having a corrupt database at worst.

    Fuentes:

    FULL backups in RMAN

    INCREMENTAL vs. FULL backups in RMAN

    Oracle has made it easy for people to not understand these backups in RMAN.

    If you're not using 10g and "true incrementals", just use full. Older versions of RMAN were not much faster because it had to do just as much reading as a full backup (read the whole datafile, backup anything that's changed). They were ONLY designed to save disk/tape speed and/or bandwidth to disk/tape. They certainly didn't speed up recovery.

    In 10g, they've FINALLY introduced a "change tracking file" and many other enhancements like incrementally Updated Backups.

    So, RMAN started out as a ham fisted tool that caused problems for a lot of people (but did help many who dedicated themselves to it), but has now become much more of an asset to the DBA.

    I use RMAN and I am glad I do. But I also use 10g. I still have problems recommending it to people on older versions.

    Read through the product docs and you can see what it offers (you'll notice RMAN doesn't have to put your tablespaces in backup mode). It also seems to be a lot easier to use nowadays, but maybe I've just gotten used to it.

    Like anything in Oracle, there are lot's of powerful tools and features for you to exploit if you know WHY to. Don't be one of those poor saps that tries to use every feature or tool just hoping that it's the proper way of doing it.


    Fuentes:

    domingo, 13 de abril de 2008

    Flash Recovery Area.

    Con la caída del costo de los discos en el mercado, los backups a disco es a menudo mas factible y funcionalmente ventajosos que los tradicionales backups a cinta. Primero, el backup a disco, elimina las restricciones de performance de la escritura en cinta , y segundo, el "time-to-recover" se reduce mediante la eliminación de la necesidad de localizar la cinta y buscar en ella la ubicación correcta desde donde iniciar la operación.

    Aprovechando esta tendencia del mercado, RMAN simplifica enormemente los backup basados en soporte de disco con la "Flash Recovery Area". La "Flash Recovery Area" es una única ubicación de storage en un filesystem o en un grupo de discos ASM (Automatic Storage Management) que organiza todos los archivos de recovery y actividades relacionados, para una base de datos Oracle.

    Todos los archivos que son necesarios para un recovery completo de una base de datos ante un media failure residen en la Flash Recovery Area, INCLUYENDO control files, archived log files, copias de los data file , y los backups de RMAN.

    Que diferencia la Flash Recovery Area de simplemente mantener backups en disco, es un conjunto de características para una administración pro-activa de backups. Por ejemplo, los backups obsoletos y archived logs que quedan fuera de la política de retención de RMAN o ya han sido almacenados a CINTA son automáticamente removidos cuando no hay espacio en disco para crear nuevos archivos. La flash recovery area informa al administrador cuando su consumo de espacio en disco está próximo a su quota definida y no hay mas archivos para eliminar. . El administrador puede entonces accionar para adicionar mas espacio al disco, , hacer backup de archivos a un tercer storage, cambiar la política de retención de RMAN, o simplemente borrar archivos. La Flash Recovery Area es administrada y configurada usando el Enterprise Manager o mediante la línea de comando.

    Fuente: http://www.oracle.com/technology/deploy/availability/pdf/rman_10g_fov.pdf

    Oracle Recovery Manager (RMAN)

    A complete high availability and disaster recovery strategy requires dependable data backup, restore, and recovery procedures. Oracle Recovery Manager (RMAN), a command-line and Enterprise Manager-based tool, is the Oracle-preferred method for efficiently backing up and recovering your Oracle database. It provides a common interface for backup tasks across different host operating systems, and offers features not available through user-managed methods, such as parallelization of backup/recovery data streams, backup files retention policy, and detailed history of all backups. The RMAN environment consists of the utilities and databases that play a role in backing up your data. At a minimum, the environment for RMAN must include the following:

    • The target database to be backed up
    • The RMAN client, which interprets backup and recovery commands, directs server sessions to execute those commands, and records your backup and recovery activity in the target database control file.

    Some environments will also use these optional components:

    • A flash recovery area, a disk location in which the database can store and manage files related to backup and recovery
    • Media management software, required for RMAN to interface with backup devices such as tape drives
    • A recovery catalog database, a separate database schema used to record RMAN activity against one or more target databases

    New Features in Oracle Database 10g Release 2
    Backup Set Encryption

    Backup security is vital to the well-being of any company. Backups should only be able to be opened and read by their creators. With Oracle Database 10gR2, backup sets made to disk can now be encrypted, for the whole database or particular tablespaces, using the new CONFIGURE ENCRYPTION FOR [DATABASE TABLESPACE …] option.

    Unused Block Compression

    With unused block compression (enabled by default), only the currently used blocks are read and written during a full backup. This speeds up backups and reduces backup size. In previous releases, blocks that are currently unused, but had been used at some point in the past, were required to continue to be backed up. Also, blocks that have never been used are never backed up.
    Dynamic Channel Allocation for RAC Environments

    By configuring the PARALLELISM parameter, RMAN will dynamically allocate the specified number of channels across all active RAC nodes, to perform the backup or restore operation. RMAN utilizes Oracle Clusterware (formerly known as Cluster Ready Services) to allocate channels to the least loaded nodes, to perform the operations. In this way, the overall backup or restore workload can be distributed across the RAC nodes more efficiently.
    Enterprise Manager Enhancements Oracle Enterprise Manager, a single, integrated solution for administering and monitoring systems and applications based on the Oracle technology stack, is further enhanced for managing and monitoring backup jobs.
    Database Control allows DBAs to view all backup jobs by date range and backup type (e.g. full, datafile, archive log), along with their status (e.g. "completed", "completed with warnings"), input and output sizes, and output rate. Each backup job can be further drilled down to review input files and output backup sets/image copies, their sizes, and compression ratio (if enabled).Grid Control offers several enhancements to manage backups across the enterprise. Backup jobs can be viewed across all target databases, and a failed job can be easily restarted without having to resubmit the job again. In case a backup job fails, the DBA can be notified immediately via email. In addition, user-defined RMAN scripts can be created as jobs and applied to any number of target databases. The recovery wizard has also been enhanced to allow restore and recovery to a different Oracle home, in the event that the original Oracle home or database is lost.

    martes, 1 de abril de 2008

    Los primeros desafios

    Estoy teniendo mis primeros inconvenientes para hacer la instalacion de ORACLE en la instancia de VMWARE.

    Una de las primeras trabas para continuar con la instalacion a sido la instalacion de las VMWARE Tools.

    El mensaje de error es

    "Error: can't create transaction lock on /var/lock/rpm/transaction"

    Y la forma de solucionarlo es ejecutar lo siguiente como Root.

    mkdir /var/local/rpm

    Para luego hacer lo siguiente (primero como usr normal y luego como root porque daba un error de permisos):

    [oracle@localhost tmp]$ cp /media/cdrecorder/VMwareTools-6.0.0-45731.i386.rpm /tmp
    cp: cannot create regular file `/tmp/VMwareTools-6.0.0-45731.i386.rpm': Permission denied
    [oracle@localhost tmp]$ su
    Password:
    [root@localhost tmp]# cp /media/cdrecorder/VMwareTools-6.0.0-45731.i386.rpm /tmpcp: overwrite `/tmp/VMwareTools-6.0.0-45731.i386.rpm'? y
    [root@localhost tmp]# rpm -Uhv /tmp/VMwareTools-6.0.0-45731.i386.rpm
    Preparing... ########################################### [100%]
    package VMwareTools-7238-45731 is already installed
    [root@localhost tmp]#


    Despues seguiré posteando errores...

    domingo, 30 de marzo de 2008

    Instalando UNBREAKABLE LINUX

    Pude instalar el Linux de Oracle que está basado en una versión de Redhat 4.0 en una máquina virtual (VMWARE) sin mayores inconvenientes.

    Despues de la instalacion uno de los Iconos de Alertas (Unbreakable Linux Network Alert Icon) avisaba de un set de actualizaciones entre las cuales se encontraba el comando up2date...

    Ahora la pregunta del millon... ¿Cómo actualizarlo?

    ¡Muy facil! desde la linea de comando 'up2date up2date' o 'up2date -u'.

    Hasta aca iba todo fenómeno pero salió un error inesperado...

    [oracle@localhost ~]$ up2date up2date
    Your GPG keyring does not contain the Enterprise Linux public key.
    Without it, you will be unable to verify that packages Update Agent downloads
    are securely signed on the Unbreakable Linux Network.

    Your Update Agent options specify that you want to use GPG.

    To install the key, run the following as root:
    rpm --import /usr/share/rhn/RPM-GPG-KEY


    [oracle@localhost ~]$ su
    Password:
    [root@localhost oracle]# rpm --import /usr/share/rhn/RPM-GPG-KEY
    [root@localhost oracle]# su oracle
    [oracle@localhost ~]$ up2date up2date



    Fuente: http://dcs.nac.uci.edu/support/sysadmin/security/archive/msg00653.html

    miércoles, 26 de marzo de 2008

    Examenes de Certificacion Oracle...

    Estoy iniciando las tratativas para empezar a rendir los examenes... para empezar a estudiar con todas las ganas... con todas las pilas para convertirme en un OCP. Jajajaja suena a puteada.

    martes, 29 de enero de 2008

    Las opciones de Shutdown de la DB (Shutdown Options)

    Oracle Database Shutdown Stages
    Oracle Metalinks, Note:110704.1.


    Las opciones de Shutdown de la base de datos son:
    • NORMAL - No se aceptan nuevas conexiones, y se espera la desconexión de todos los usuarios. Se cierra y desmonta la base de datos previo al shutdown, y no requiere realizar "instance recovery" en el próximo startup de la base de datos.
    • IMMEDIATE - Realiza el Rollback de todas las transacciones sin confirmar (uncommitted txns) y desconecta todos los usuarios. Cierra y desmonta la Base de Datos antes del shutdown, y no requiere de recovery posterior en el próximo startup de la base de datos.
    • TRANSACTIONAL - No acepta nuevas conexiones, y los usuarios son desconectados cuando las transacciones actuales se completan. Una vez hecho esto se ejecuta un shutdown IMMEDIATE.
    • ABORT - Todas las transacciones son finalizadas, ninguna transacción es "deshecha" (rolled back), la instancia se cierra sin realizar el cierre de los data files y el próximo startup de la base de datos requerirá un "instance recovery".

    Introducción a SQLPlus

    Desde linea de comando de sistema, estos son algunos de los parámetros que recibe el SQLPLUS:

    sqlplus /nolog
    sqlplus userid/passwd@db
    sqlplus @miscript

    Un ejemplo es:

    sqlplus /nolog
    SQL> connect sys/passwd as SYSDBA
    SQL> select * from v$instance;
    SQL> disconnect
    SQL> exit


    Estos son algunos de los comandos que recibe el SQLPLUS con los cuales pueden setearse opciones, ejecutar archivos de Scripts o correr instrucciones en el HOST:

    • SHOW USER -- Para saber con qué usuario estás conectado.
    • EDIT -- Abre el editor.
    • EXIT -- Termina la conexión.
    • GET -- Extrae el contenido de un archivo con comandos sql.
    • HOST -- ejecuta comandos de sistema operativo.
    • LIST -- muestra el ultimo comando.
    • RUN -- Ejecuta el contenido del buffer.
    • SAVE -- Guarda los comandos sql en archivo.
    • SET -- cambia el ambiente de SQLPLUS
    • SHOW -- muestra la configuración vigente.
    • SPOOL -- Envia salida a un archivo.
    • START -- Ejecuta el contenido SQL de un archivo.
    • SET SQLPROMPT -- Cambia el prompt.

    ¿Cómo activar TRACE sobre comandos sql? (Para ampliar el número de columnas que se despliegan, se recomienda eluso del comando "SET LONG ")

    SQL> SET AUTOTRACE ON

    El comando AUTOTRACE permite ver las estadisticas y/o plan de ejecucion para las sentencias DML. Y las opciones del AUTOTRACE son las siguiente:

    • AUTOTRACE ON
    • AUTOTRACE TRACEONLY
    • AUTOTRACE OFF
    • AUTOTRACE ON EXPLAIN
    • AUTOTRACE ON STATISTICS
    • AUTOTRACE ON EXPLAIN STATISTICS
    • AUTOTRACE TRACEONLY EXPLAIN
    • AUTOTRACE TRACEONLY STATISTICS
    • AUTOTRACE TRACEONLY EXPLAIN STATISTICS
    • AUTOTRACE OFF EXPLAIN
    • AUTOTRACE OFF STATISTICS
    • AUTOTRACE OFF EXPLAIN STATISTICS

    La opcion ON muestra ambas, estadisticas y plan de ejecución. ON EXPLAIN solo mostrará el plan de ejecucion y ON STATISTICS solo mostrara las estadisticas. La opcion TRACEONLY que reemplaza al ON, ocasiona que NO se muestren los datos que devolveria la consulta. La opcion OFF deshabilita todas las opciones previamente ingresadas.

    Fuentes

    ¿Cómo habilitar AUTOTRACE en SQLPLUS?

    El parámetro de AUTOTRACE puede habilitarse con la siguiente instrucción dentro del SQLPLUS.

    SQL> SET AUTOTRACE ON

    Recibiremos el siguiente error en caso de no estar habilitado, no existir la tabla o no tener el rol correspondiente asignado:

    ora816 SamSQL :> set autotrace on;
    SP2-0613: Unable to verify PLAN_TABLE format or existence
    SP2-0611: Error enabling EXPLAIN report
    SP2-0618: Cannot find the Session Identifier. Check PLUSTRACE role is enabled
    SP2-0611: Error enabling STATISTICS report

    La forma de corregir esto es ejecutar los siguientes scripts


    1. Ejecutar plustrce.sql en el esquema SYS

    NT :- @$ORACLE_HOME\sqlplus\admin\plustrce.sql
    UNIX :- @$ORACLE_HOME/sqlplus/admin/plustrce.sql

    2. Grant PLUSTRACE al usuario que desea hacer el AUTOTRACE:

    La tabla PLAN_TABLE debe existir en el esquema del usuario, para la creación de la tabla necesitamos ejecutar el script UTLXPLAN.sql en el esquema del usuario, este script puede encontrarse en :

    NT :- $ORACLE_HOME\rdbms\admin\utlxplan.sql
    UNIX :-$ORACLE_HOME/rdbms/admin/utlxplan.sql

    Ver post de "Introducción a SQLPLUS" para ver las opciones del comando SET AUTOTRACE.