Tipos de Datos en Oracle: Guía Completa
Tipos de Datos en Oracle: Guía Completa
CHAR
CHAR(n BYTE|CHAR) Almacena n(max 2000) caracteres, en bytes o char (default en
NLS_LENGTH_SEMANTICS) si se crea en SYS, es en bytes
NCHAR (n) Almacena n(max 2000) caracteres permitiendo ASCII, UNICODE, que ocupan 2 o 3
bytes según el character set. (AL16UTF16 2b, UTF8 3b)
VARCHAR2(n BYTE|CHAR) Almacena hasta n caracteres. El máximo depende del valor de MAX_STRING_SIZE
(4000 si STANDARD, 32767 si EXTENDED) , en bytes o char (default en
NLS_LENGTH_SEMANTICS). Ojo no poner valores al pedo, porque en una query
Oracle prealoca el maximo de memoria.
NVARCHAR2(n) VARCHAR2 para Unicode, ASCII
LOB
CLOB Character Large Object. Hasta (4GB- 1) * (database block size)
NCLOB Character Large Object+ unicode. Hasta (4GB- 1) * (database block size)
BLOB Binario. Hasta (4GB- 1) * (database block size)
BFILE Referencia a un archivo externo hasta 4GB
LONG AND RAW
RAW No se usa mas, usar BLOB. 2000/32767( MAX_STRING_SIZE = ST / EXT)
LONG RAW No se usa mas, usar BLOB. Hasta 2 gb
LONG Hasta 2gb-1. No se usa mas, usar CLOB.
NUMBER
NUMBER(e,d) 38-position. d puede ser negativo;: 10,-2 significa redondeo a centena.
Nros +/-. Infinito. FLOAT ocupan menos.
Si pongo solo NUMBER, es un float del mayor rango.
BINARY_FLOAT 32 bits. ocupa 4 bytes. Puede tener un punto decimal donde sea o no tenerlo.
Aceptan infinito, 1.377e-20,NaN
BINARY_DOUBLE 64 bits. ocupa 8 bytes
FLOAT(n) [Link] es type number. Almacena como binario (?). si pongo
float(5), el valor no puede superar los 5 digitos binarios. (31 es el > q puede
representarse con 5) entonces 123.45 es redondeado a 120. Lo usa Oracle
internamente.
DATETIME
DATE 7-byte, representa timestamp en gregoriano, por defecto DD-MON-RR, segun
NLS_DATE_FORMAT en tabla V$PARAMETER
INTERVAL YEAR(p) TO 5-byte, almacena periodo en años y meses. por ejemplo insertamos INTERVAL '10-
MONTH 2' YEAR TO MONTH, 10 años y dos meses. P: digitos en year.
INTERVAL DAY(p1) TO 11-byte almacena periodo en dia hora minuto segundo. INTERVAL '11 10:09:08.555'
SECOND(p2) DAY TO SECOND. P1: digitos en year, p2:d igitos en seg.
TIMESTAMP(s) 7- to 11-byte representa fecha y hh, mi ,ss. si se pone presicion, es para la fraccion
de segundos(0-9), default 6. Formato según NLS_TIMESTAMP_FORMAT
TIMESTAMP WITH [LOCAL] 13-byte incluye offset para UTC
TIME ZONE LOCAL, cada uno ve horario de su sesión, data se guarda con zona de la DB
ROWID
ROWID 10-byte representa la pseudocolumna rowid
UROWID(n) Hasta 4000 bytes es rowid en tablas indexadas o non-Oracle.
XMLType(n) Hasta 4000 bytes, representa XML y existen funciones builtin para trabajar.
BOOLEAN Es PLSQL
%type Crea componente basado en formato y tipo de una columna de tabla o vista
%rowtype Crea registro basado en estructura de tabla o vista.
Tipos numéricos
+-2,147,483,648. 32 [Link] menos y las cuentas tardan menos que los NUMBER.
PLS_INTEGER Para valores mayores a esos usar INTEGER. Subtipos: NATURAL, NATURALN (not null),
POSITIVE,POSITIVEN, SIGNTYPE (-1,0,1)
Subtipo de PLS_INTEGER, mismo rango, not null. Si sabemos que nuestra variable no va a ser nula ni
SIMPLE_INTEGER superar rango es mejor utilizar esta que pls_integer.
Son de ancho fijo. Para comparacion usar función trunc. Tiene estos campos:
YEAR -4712 to 9999 (no 0), MONTH, DAY, HOUR, MINUTE, SECOND.
DATE
mas los campos de zona: TIMEZONE_HOUR/MINUTE/REGION/ABBR. Estos se extraen de
SYSTIMESTAMP, no SYSDATE
Extiende DATE y la presición son los decimales de segundos. El formato es según
TIMESTAMP(p)
NLS_TIMESTAMP_FORMAT. Hasta mil millonésima de segundo.
TIMESTAMP WITH La zona respecto a UTC expresada como -07.00 por ejemplo. El formato viene dado por
TIMEZONE NLS_TIMESTAMP_TZ_FORMAT en V$NLS_PARAMETERS
BFILE Almacenado fuera de la DB, hasta 4GB o según S.O. Accesible desde app pero ReadOnly
Dentro de la DB 8 a 128 tb. Persistentes en la DB, aplican propiedades ACID. Temporales
BLOB/CLOB/NCLOB
(var en mi app)
Son locales a menos que esten definidas en pkg y se referencia anteponiendo pkg.
Similares a una fila de una tabla. Se declaran explicitamente , basada en cursor o tabla con
%rowtype.
Primero creamos tipo, luego el registro:
TYPE Registro is RECORD (campo tipo_campo(l) [NOT NULL := algo])
Miregistro Registro.
RECORD
Se referencia con qualifier y dot notation: [Link]
Se le asigna valores desde select, fetch, otro registro (aggregate).
NESTED RECORDS: cuando uno de los campos es a su vez RECORD. y se referencia con
qualifier y dot notation adicional.
Si se define en un package, se puede referenciar con nombre_pkg.registro
Estructura unidimensional con elementos del mismo tipo. key-value. Assoc-Array|index table
Primero creamos tipo, luego la tabla:
TYPE Registro is TABLE OF (tipo_campo(ix) [NOT NULL] index by BINARY_INTEGER|VARCHAR2
No se inicializan en la declaración.
Se referencia con qualifier y dot notation y la referencia a la primary key entre paréntesis:
tabla(v_indice) o tabla(v_indice).campo si está basada en Record.
TABLE Se pueden hacer cuentas o concatenar v_indice
Se puede asignar una tabla a otra (sobreescribiendo la segunda).
ASSOC-ARRAY
Metodos: se aplican a [Link]([indice1,[indice2]])
Tabla basada en record tiene que tener campos escalares (no nested records)
INDEX BY
TABLE Pero en una tabla de la DB puedo poner una columna que sea tabla (nested table)
Si lo declaro como Constante, tengo que crear una funcion que la lleve, como un constructor.
NESTED TABLE: Si la colección no tiene index by, es una nested table o si tiene una columna
de tabla que tenga filas. indexado por number;
Al traerlas, se las pasa a una variable asignando indice desde 1. El orden puede no siempre ser
el mismo. Usando funciones set / multiset traigo datos de una columna de tipo NT.
Debe inicializarse
Estructura unidimensional con elementos del mismo tipo. Es limitada (aunque puede
extenderse) Cada elemento se le asigna un indice que arranca en 1, sin faltantes.
Primero creamos tipo, luego varray: TYPE varray1 is VARRAY(longitud) OF Tipovalor.
Al declararlo está nulo. Puede inicializarse en la declaracion. (tiene constructor)
VARRAYS
TYPE T1 IS VARRAY(3) OF NUMBER;
TYPE T2 IS VARRAY(2) OF T1; Desde 9i se puede anidar Luego se referencia VEC1(a)(b)
Vec0 T1 := T1(1,2,3);
Vec1 T2 := T2(T1);
User Defined Types. Creamos un objeto y luego tabla de objetos.
Como Classes en otros lenguajes con sus constructores y funciones. Soportan herencia y
polimorfismo. Las manejamos como cualquier colección.
SQL UDT
CREATE TYPE hobbit IS OBJECT (...) [NOT] INSTANTIABLE [NOT] FINAL;
Pueden usarse como columnas de una tabla. Se implementan cuando definimos BODY:
CREATE TYPE BODY hobbit IS....
Manejo xml en tabla, se pasa como pará[Link] con operadores, funciones, validador.
my_xml XMLTYPE;
XMLTYPE my_xml := XMLTYPE('<root><element>value</element></root>');
SELECT ExtractValue(Value(p),'/root/element') AS elemento FROM
TABLE(XMLSequence(my_xml.extract('//root'))) p)
URI
ANY
EXISTS(n) Returns TRUE if the nth element in a collection exists; otherwise returns FALSE.
COUNT Returns the number of elements that a collection currently contains.
LIMIT Checks the maximum size of a collection.
Returns the first (smallest) index numbers in a collection that uses the integer
FIRST
subscripts.
Returns the last (largest) index numbers in a collection that uses the integer
LAST
subscripts.
PRIOR(n) Returns the index number that precedes index n in a collection.
NEXT(n) Returns the index number that succeeds index n.
EXTEND Appends one null element to a collection.
EXTEND(n) Appends n null elements to a collection.
EXTEND(n,i) Appends n copies of the ith element to a collection.
TRIM Removes one element from the end of a collection.
TRIM(n) Removes n elements from the end of a collection.
DELETE Removes all elements from a collection, setting COUNT to 0.
Removes the nth element from an associative array with a numeric key or a nested
DELETE(n) table. If the associative array has a string key, the element corresponding to the key
value is deleted. If n is null, DELETE(n) does nothing.
DELETE(m,n) Elimina rango m..n de un ass-arr/nested table. m<n, no null. Sino no hace nada.
Collection Exceptions
Collection Pseudofunctions
Mapea una tabla a una coleccion. Junto con CAST podemos traer una fila como una
MULTISET columna
SELECT CAST (MULTISET (SELECT field FROM table) AS collection-type) FROM DUAL;
Mapea coleccion a una tabla (algo q pueda ser selectable) . Inverso de Multiset.
TABLE
TABLE(scope_name.collection_name) . Ver TABLE FUNCTION
Consultas
INNER JOIN
SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date
FROM suppliers
INNER JOIN orders -- REGISTROS DE LA PRIMERA Q ESTEN EN LA SEGUNDA
ON suppliers.supplier_id = orders.supplier_id;
LEFT OUTER JOIN
SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date
FROM suppliers -- REGISTROS DE LA PRIMERA AUNQUE NO ESTEN EN SEGUNDA, IGUAL A
SELECT CON (+)
LEFT OUTER JOIN orders
ON suppliers.supplier_id = orders.supplier_id;
RIGHT OUTER JOIN
SELECT orders.order_id, orders.order_date, suppliers.supplier_name
FROM suppliers -- REGISTROS DE LA 2DA AUNQUE NO ESTEN EN 1RA, IGUAL A SELECT
CON (+)
RIGHT OUTER JOIN orders
ON suppliers.supplier_id = orders.supplier_id;
FULL OUTER JOIN
SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date
FROM suppliers -- TODOS LOS REGISTROS DE AMBAS TABLAS , IGUAL A SELECT CON
UNION
FULL OUTER JOIN orders
ON suppliers.supplier_id = orders.supplier_id;
USING
SELECT [Link], [Link] -- TOMA CAMPOS DEL MISMO NOMBRE
FROM table1 JOIN table2 USING ([Link],[Link])
NATURAL JOIN
SELECT [Link], [Link] -- TOMA CAMPOS DEL MISMO NOMBRE
FROM table1
NATURAL JOIN table2
NONEQUIJOINS : cuando las tablas no tienen campo en comun, pero si una condicion
select a.x,b.y from a join b on a.x between b.a and b.b
PIVOT
SELECT * FROM ( SELECT customer_ref, product_id FROM orders)
PIVOT
(COUNT(product_id) - siempre una funcion de agrupacion.
FOR product_id IN (10, 20, 30) para estos productos )
ORDER BY customer_ref;
LIKE
SELECT ... WHERE job_id LIKE 'SA\_%' ESCAPE '\'; (EL GUION BAJO REEMPLAZA UN CARACTER)
IN, ANY, SOME
SELECT DESCRIPCION FROM TABLA WHERE CODIGO = ANY/SOME/ALL (SELECT CODIGO FROM TABLA2
WHERE...) ALGUN VALOR QUE COINCIDA
& (AMPERSAND)
SELECT.....WHERE C1 = &V1 OR C2 = &V2
EL & VA A PEDIR UN valor por cada ocurrencia. Doble Ampersand pide el valor una sola vez
Commit;
SET AUTOCOMMIT ON;
-- and to turn it off
SET AUTOCOMMIT OFF;
ROLLBACK [TO SAVEPOINT savepoint_name];
SAVEPOINT savepoint_name ;
SET TRANSACTION: Permite establecer una sesión como solo de lectura o lectura/escritura, hasta un
rollback o commit (aunque no haga falta). Todas las queries dentro de la transacción solo ven cambios
commiteados antes del comienzo de la transacción
Transacciones autónomas: Permite que las actividades dentro de un subprograma no afecten las
transacciones externas. Es decir COMMIT, ROLLBACK dentro de este programa no afecta a otros.
Para esto, escribimos PRAGMA AUTONOMOUS_TRANSACTION en la declarativa del programa. Antes de salir
del programa, es obligatorio finalizar la transacción.
PL/SQL: Operators / Conditions / Iterations
Apóstrofes: Si está al comienzo o final, Select ''' para que se vea uno. Si está al medio, uso ''. Si es una
concatenación, uso ''''
También uso q' para todo: q'[]' o cualquier par (),<>,!!,¡¡
Comparison Operators
Operator Description
LIKE Compara string o CLOB contra un patrón.
BETWEEN Se cumple si un valor está entre otros dos. x BETWEEN a AND b significa x >= a y x <= b.
IN x IN (valores). Testea si x está entre algunos de los valores.
IS NULL Devuelve TRUE o FALSE
IS [NOT] chequea si el operador esta o no vacio. se aplica a varray o table colection. Tiene que estar
EMPTY inicializado para que funcione.
The IS SET comparison operator checks whether the left operand holds a set of elements,
IS SET
and only applies when the left operand is a varray or table collection data type.
Logical Operators
Operator Description
and TRUE AND NULL = NULL, FALSE AND NULL = FALSE
or TRUE OR NULL = TRUE, FALSE OR NULL = FALSE
not Called the logical NOT Operator.
Conditions / Iterations
mas de 32k de dtos se manejan con dbms_lob package. pueden estar null, empty, populated. no se
puede cargar mas de 32k con insert, hay que usar una funcion con RETURNING INTO en el insert.
des_clob CLOB;
src_clob BFILE := BFILENAME('GENERIC',src_file_name);
des_offset NUMBER := 1;
src_offset NUMBER := 1;
src_size INTEGER;
ctx_lang NUMBER := dbms_lob.default_lang_ctx;
warning NUMBER;
stmt VARCHAR2(2000);
BEGIN
IF dbms_lob.fileexists(src_clob) = 1 AND NOT dbms_lob.isopen(src_clob) = 1 THEN
src_size := dbms_lob.getlength(src_clob);
dbms_lob.open(src_clob,DBMS_LOB.LOB_READONLY);
END IF;
stmt := 'UPDATE '||table||''SET '||column||' = empty_clob() 'WHERE '||p_k_n||' = '||''''|| p_k_v||''' ' ||
'RETURNING '||column||' INTO :locator';
EXECUTE IMMEDIATE stmt USING OUT des_clob;
dbms_lob.loadclobfromfile( dest_lob => des_clob
, src_bfile => src_clob , amount => dbms_lob.getlength(src_clob)
, dest_offset => des_offset , src_offset => src_offset
, bfile_csid => dbms_lob.default_csid , lang_context => ctx_lang , warning => warning );
dbms_lob.close(src_clob);
IF src_size = dbms_lob.getlength(des_clob) THEN
$IF $$DEBUG = 1 $THEN dbms_output.put_line('Success!'); $END
ELSE
$IF $$DEBUG = 1 $THEN dbms_output.put_line('Failure.'); $END
RAISE dbms_lob.operation_failed;
END IF;
END load_clob_from_file;
PL/SQL: Functions - procedures
PL/SQL: Packages
En la especificación se declaran los items públicos. Comparte definiciones y opciones
que vimos en funciones.
Las Funciones en packages admiten overloading (cambio de tipo y nro de parámetros,
no el nombre). Si hay cursores o subprogramas, tiene que tener un cuerpo.
En el cuerpo puedo declarar items privados.
Puedo declarar cursor en la definición y definirlo (select...) en el cuerpo, asi no se ve.
En cualquiera de las dos partes se puede mapear un procedimiento externo (java,c)
con call specification.
Los valores almacenados persisten durante la vida de la llamada del bloque sevidor.,
mientras que los no serially, duran toda la sesion.
AUTHID {DEFINER|CURRENT USER}: en la especificación determina si los programas
corren con el privilegio del Definer o del usuario y como resolver la referencia a objetos
en qcuál esquema.
cuando una sesión invoca a un package, Oracle crea una instancia y lo inicializa.
Package state: son los valores de las variables, constantes y cursores. Si no hay, es
stateless.
pragma SERIALLY_REUSABLE: mejora el uso de memoria. el estado se guarda en un
area de trabajo de memoria. Oracle puede reutilizar la instancia que está en ese pool
de memoria. De lo contraria se almacena en memoria para cada usuario.
No se usan para triggers DB, o subprograma invocado por una instruccion SQL.
PL/SQL: Cursors
Punteros a datos que Oracle asigna en memoria (context area). No se puede ir para atras. Implicitos, se crean con cada
DML.
OPEN cursor LOOP.. FETCH cursor into.... EXIT WHEN...END LOOP... CLOSE cursor.
Un cursor puede tener parametros, como una función. CURSOR c1 (a NUMBER,b VARCHAR2) IS
Puedo usar un cursor para updatear datos. Oracle lockea esos registros hasta que el cursor se cierra o commit o rollback
FOR UPDATE [of columna1[,columna2]] WAIT seconds | NOWAIT: no espera a unlock.
UPDATE/DELETE WHERE CURRENT OF cursor :actualiza, borra el registor en cuestion.
Cursor Variable: es una variable que referencia a un cursor. No está asignada a ninguna query específica, es decir se
puede abrir para cualquier query. Y puede pasarse entre rutinas.
TYPE c1 IS REF CURSOR RETURN tabla%rowtype-- (strong type, porque está asociada a una estructura).
TYPE c2 IS REF CURSOR --es weak type o puede usarse el tipo definido SYS_REFCURSOR.
c3 c2
OPEN c2 FOR SELECT ...
RETURN c2 -- Devuelve un SYS_REFCURSOR que se asigna a variable y se procesa como cualquier cursor.
Atributos de cursores (anteponer SQL para implícitos, el nombre del cursor para explícitos)
%FOUND TRUE si una sentencia DML (o SELECT into) afectó a una o mas fila.
Al compilar, PL nos avisa de los [Link] ver la vista ??_ERRORS o SHOW ERRORS segun donde
estemos. Categorias: SEVERE,PERFORMANCE,INFORMATIONAL.
Seteando PLSQL_WARNINGS prendemos apagamos o decimos como manejar los warnings. Con alter system,
alter session o alter statements. El valor actual esta en la vista ALL_PLSQL_OBJECT_SETTINGS.
ALERT SYSTEM|SESSION|PROCEDURE X SET|COMPILE PLSQL_WARNINGS='ENABLE|DISABLE:ALL|CATEG
DBMS_WARNING , tiene subprogramas para setear o ver valores de warnings en la sesión.
Para capturar errores en DECLARE, conviene encerrar la sección en otro BEGIN EXCEPTION END.
SQLCODE,SQLERRM(codigo): Nos da codigo y mensaje de error. No pueden usarse en una instrucción SQL
Conviene usar (a menos que estemos en un FORALL)
DBMS_UTILITY.FORMAT_ERROR_STACK: Nos da el nro de error
DBMS_UTILITY.FORMAT_ERROR_BACKTRACE: Nos muestra proceso y linea de donde viene el error
BULK OPERATIONS
BULK COLLECT: trae muchas filas en un solo fetch. Trae todo a una collection index by PLS_INTEGER. Evita
idas y vueltas entre PLSQL y SQL.
SELECT .... BULK COLLECT INTO (Table) [LIMIT 1000].
Si no encuentrala colección está vacía, arranca en 1, es densa y solo enteros. No s einicializa ni extiende (si
lo lleno en un varray).
Luego se trabaja con como cursores o FORALL
OPEN A1
FETCH A1 BULK COLLECT INTO TABLA LIMIT 1000 EXIT WHEN [Link] = 0;
FOR x in 1..[Link] LOOP tabla(x).campo .......END LOOP
CLOSE A1
PL/SQL: Triggers
PL blocks que se ejecutan antes, despues o en lugar de un evento. Se guardan en LONG asi q max 32k. Se
ejecutan automaticamente. A nivel tabla, vistas, esquemas o DB.
Eventos: DML, DDL, logon, startup, servererror. 12 max por tabla.
Se administran con ALTER TRIGGER nombre [COMPILE|ENABLE|DISABLE] y también a nivel tabla ALTER
TABLE tabla [ENABLE|DISABLE] ALL TRIGGERS. DROP TRIGGER nombre.
RETURNING INTO: Especifica las variables dondes se almacenan los resultados devueltos por una instrucción.
Static: I,U,D; Dyn: ExIm. Solo si devuelve una fila, a menos que sea con bulk collect. Aparece en la
instrucción y en 'USING...'
x := 'UPDATE A SET B=:1 WHERE ID=:2 RETURNING columna [bulk collect] INTO :3';
EXECUTE IMMEDIATE X USING a,b RETURNING INTO c;
Puede ser Objetos o Objeto que tiene una coleccion anidada. SELECT *
(multilevel) FROM TABLE(
CREATE OR REPLACE SELECT CAST(COLLECT(
TYPE prominent_object IS OBJECT ( N V2(20) , a V2(10)); people_object( 'Men' ,
CREATE OR REPLACE prominent_object('Aragorn','3rd Age') )
TYPE people_object IS OBJECT ( race VARCHAR2(10) , ) AS people_table ) FROM dual);
exemplar PROMINENT_OBJECT);
CREATE OR REPLACE FUNCION COLLECT: Toma como argumento
TYPE people_table IS TABLE OF people_object; columna y genera nested table del select
que hace. se tiene que ver con CAST
CAST convierte un tipo en otro.
No se puede inicializar como v_a('a','b') pq tiene indice. V_A(indice) = valor. No tienen que ser
secuenciales, puede ser cualquier entero. Cuando se trabaja con Objetos, se carga por indice con
constructor, se referencia por el nombre del campo:
Puedo cargar un cursor en un array que sea rowtype con array(x) := cursor;
ACTION Identifies the position in the module. You use the dbms_application_info
package to set the value
AUDITED_CURSORID Returns the cursor ID of the SQL statement that triggered an audit
event. It is not a valid value when you’re using fine-grain auditing, in
which case it returns a null
AUTHENTICATED_IDENTITY Returns the authenticated identity in a format that differs by type of
authentication, like Kerberos, SSL, password, OS, Radius, proxy, or
SYSDBA/SYSOPER
AUTHENTICATION_DATA Containsvalue to authenticate the user, which may be an X.503
certificate
AUTHENTICATION_METHO Returns the authenticated method, like Kerberos, SSL, password,OS,
D Radius, proxy, or background process.
BG_JOB_ID Returns the current session identifier established by a background DB
process
CLIENT_IDENTIFIER Returns an identifier set by calling the SET_IDENTIFIERprocedure from
the dbms_session package, the OCI_ATTR_CLIENT_IDENTIFIER attribute,
or the setClientIdentifier method of the Java class
[Link]
CLIENT_INFO Returns a 64-byte character string set by calling the SET_CLIENT_INFO
procedure of the dbms_application_info package
.
.
CURRENT_BIND Returns bind variables or fine-grain auditing.
CURRENT_EDITION_NAME Returns the edition in use by the current session.
CURRENT_EDITION_ID Returns the identifier of the edition in use by the current session.
CURRENT_SCHEMA Returns the current schema name, which you can change by
calling the ALTER SESSION SET CURRENT_SCHEMA statement.
CURRENT_SCHEMAID Returns the current schema identifier, which you can change by
calling the ALTER SESSION SET CURRENT_SCHEMA statement.
CURRENT_SQL or
CURRENT_SQLn
Returns the first 4KB of the current SQL statement that triggered
fine-grain auditing. You use CURRENT_SQLn (where n is an
integer) to get the next 4KB of the current SQL statement.
CURRENT_SQL_LENGTH Returns the byte length of the SQL statement that triggered
a fine-grain auditing event.
DB_DOMAIN Returns the database initialization parameter of the same name
when it is set.
DB_NAME Returns the database initialization parameter of the same name
when it is set.
DB_UNIQUE_NAME
Returns the database initialization parameter of the same name
ENTRYID
Returns the current audit entry number. This sequence value is
shared between regular and fine-grain auditing and cannot be
used in distributed scope.
ENTERPRISE_IDENTITY
Returns the user’s enterprise-wide identity, which is an OID value
set as the DN value.
FG_JOB_ID Returns the current session identifier when established by
a foreground database process.
GLOBAL_CONTEXT_MEMORY
Returns the number being used in the SGA by the globally
accessed context.
GLOBAL_UID Returns the current session identifier when established by
a background database process.
HOST Returns the machine hostname value.
IDENTIFICATION_TYPE Returns the method used to establish the current session, as follows:
LOCAL when identified by password
EXTERNAL when identified externally
GLOBAL SHARED when identified globally
GLOBAL PRIVATE when identified globally by DN
INSTANCE Returns the identification number of the current instance.
INSTANCE_NAME Returns the name of the current instance.
IP_ADDRESS Returns the IP address for the server or virtual machine running
the instance.
ISDBA Returns true when the current user has DBA privileges and returns false when they do
not.
LANG Returns the ISO abbreviation for the language name.
LANGUAGE Returns the language and territory currently in use and the character set
separated by a period.
MODULE Returns the application name set by the SET_MODULE procedure in the
dbms_application_info package.
NETWORK_PROTOCOL Returns network protocol value for a connection.
NLS_CALENDAR Returns the current session’s calendar.
NLS_CURRENCY Returns the current session’s currency.
NLS_DATE_FORMAT Returns the current session’s default date format.
NLS_DATE_LANGUAGE Returns the current session’s language for expressing dates.
NLS_SORT Returns the current session’s linguistic sort basis or the default BINARY.
NLS_TERRITORY Returns the current session’s territory.
OS_USER Returns the operating system user account that initiated the current database
session.
POLICY_INVOKER Returns the invoker of row-level security (RLS) policy function.
PROXY_ENTERPRISE_IDENTITY
Returns the Oracle Internet Directory DN when the proxy user is
an enterprise user.
PROXY_GLOBAL_UID Returns the global user identifier from the Oracle Internet
Directory for Enterprise User Security (EUS) proxy users, or null
for all other proxy users.
PROXY_USER Returns the user name of the database user who opened the
current session on behalf of the SESSION_USER.
PROXY_USERID Returns the user identifier of the database user who opened the
current session on behalf of the SESSION_USER.
SERVER_HOST Returns the server hostname.
SERVICE_NAME Returns the service hostname.
SESSION_EDITION_NAME Returns the edition in use by the current session.
SESSION_EDITION_ID Returns the edition identifier in use by the current session.
SESSION_USER Returns the schema for Enterprise users, and the database user
name by which the current session is authenticated.
SESSION_USERID Returns the database user identifier by which the current session
is authenticated.
SESSIONID Returns the auditing session identifier.
SID Returns the session number, which is different from the session
identifier.
STATEMENTID Returns the number of the SQL statement audited in a given
session. This attribute cannot be used in distributed scope.
TERMINAL Returns the server hostname
when it is set.
SQL LOADER
.ctl
LOAD DATA
INFILE 'path\FILE'
TRUNCATE
INTO TABLE table
FIELDS TERMINATED BY ","
(col1, col2..., col n)
AUDITED_CURSORID Returns the cursor ID of the SQL that triggered the audit. This
parameter is not valid in a fine-grained auditing environment.
If you specify it in such an environment, then Oracle
Database always returns null.
AUTHENTICATION_DATA Data being used to authenticate the login user. For X.503
certificate authenticated sessions, this field returns the
context of the certificate in HEX2 format.
Note: You can change the return value of
the AUTHENTICATION_DATA attribute using
the length parameter of the syntax. Values of up to 4000 are
accepted. This is the only attribute of USERENV for which
Oracle Database implements such a change.
Parameter Return Value
CLIENT_PROGRAM_NAME The name of the program used for the database session.
Parameter Return Value
CURRENT_BIND The bind variables for fine-grained auditing. You can specify
this attribute only inside the event handler for the fine-
grained auditing feature.
CURRENT_SCHEMA The name of the currently active default schema. This value
may change during the duration of a session through use of
an ALTER SESSION SET CURRENT_SCHEMA statement. This
may also change during the duration of a session to reflect
the owner of any active definer's rights object. When used
directly in the body of a view definition, this returns the
default schema used when executing the cursor that is using
the view; it does not respect views used in the cursor as
being definer's rights.
Note: Oracle recommends against issuing the SQL
statement ALTER SESSION SET CURRENT_SCHEMA from
within all types of stored PL/SQL units except logon triggers.
CURRENT_SQL_LENGTH The length of the current SQL statement that triggers fine-
grained audit or row-level security (RLS) policy functions or
event handlers. You can specify this attribute only inside the
event handler for the fine-grained auditing feature.
DRAIN_STATUS Displays the draining status for the current session. If the
session is a candidate for drain, returns DRAINING, else
returns NONE.
ENTRYID The current audit entry number. The audit entryid sequence
is shared between fine-grained audit records and regular
audit records. You cannot use this attribute in distributed SQL
statements. The correct auditing entry identifier can be seen
only through an audit handler for standard or fine-grained
audit.
GLOBAL_CONTEXT_MEMORY Returns the number being used in the System Global Area by
the globally accessed context.
GLOBAL_UID Returns the global user ID (GUID) from Active Directory for
Centrally Managed Users (CMU) logins, or from Oracle
Internet Directory for Enterprise User Security (EUS) logins.
Returns null for all other logins.
HOST Name of the host machine from which the client has
connected.
IDENTIFICATION_TYPE Returns the way the user's schema was created in the
database. Specifically, it reflects the IDENTIFIED clause in
the CREATE/ALTER USER syntax. In the list that follows, the
syntax used during schema creation is followed by the
identification type returned:
IDENTIFIED BY password: LOCAL
IDENTIFIED EXTERNALLY: EXTERNAL
IDENTIFIED GLOBALLY: GLOBAL SHARED
IDENTIFIED GLOBALLY AS DN: GLOBAL PRIVATE
GLOBAL EXCLUSIVE for exclusive global user mapping.
GLOBAL SHARED for shared user mapping.
NONE when the schema is created with no authentication.
LANG The abbreviated name for the language, a shorter form than
the existing 'LANGUAGE' parameter.
Parameter Return Value
ORACLE_HOME The full path name for the Oracle home directory.
PLATFORM_SLASH The slash character that is used as the file path delimiter for
your platform.
PROXY_USER Name of the database user who opened the current session
on behalf of SESSION_USER.
SESSION_USER The name of the session user (the user who logged on). This
may change during the duration of a database session as
Real Application Security sessions are attached or detached.
For enterprise users, returns the schema. For other users,
returns the database user name. If a Real Application
Security session is currently attached to the database
session, returns user XS$NULL.
See Also: Oracle Database 2 Day + Security Guide for more
information on user XS$NULL
SESSION_USERID The identifier of the session user (the user who logged on).
SESSIONID The auditing session identifier. You cannot use this attribute
in distributed SQL statements.
TERMINAL The operating system identifier for the client of the current
session. In distributed SQL statements, this attribute returns
the identifier for your local session. In a distributed
environment, this is supported only for
remote SELECT statements, not for remote INSERT, UPDATE,
or DELETE operations. (The return length of this parameter
may vary by operating system.)