09.11.2014 Views

Funciones a Nivel de Fila

Funciones a Nivel de Fila

Funciones a Nivel de Fila

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

3<br />

<strong>Funciones</strong> a <strong>Nivel</strong> <strong>de</strong> <strong>Fila</strong><br />

Copyright © Oracle Corporation, 1998. All rights reserved.


Objetivos<br />

Al completar esta lección, <strong>de</strong>bería ser<br />

capaz <strong>de</strong> hacer lo siguiente:<br />

• Explicar los diversos tipos <strong>de</strong><br />

funciones disponibles en SQL.<br />

• Incluir una variedad <strong>de</strong> funciones <strong>de</strong><br />

caracteres, numéricas y <strong>de</strong> datos en<br />

sentencias SELECT.<br />

• Explicar las funciones <strong>de</strong> conversión y<br />

la manera en que podrían ser usadas.<br />

3-2 Copyright © Oracle Corporation, 1998. All rights reserved.


<strong>Funciones</strong> SQL<br />

Entrada<br />

Función<br />

Salida<br />

arg 1<br />

arg 2<br />

arg n<br />

Las <strong>Funciones</strong><br />

Realizan<br />

Acciones<br />

Valor<br />

Resultado<br />

3-3 Copyright © Oracle Corporation, 1998. All rights reserved.


Dos Tipos <strong>de</strong> <strong>Funciones</strong> SQL<br />

<strong>Funciones</strong><br />

<strong>Funciones</strong> a<br />

<strong>Nivel</strong> <strong>de</strong> <strong>Fila</strong><br />

<strong>Funciones</strong> a<br />

<strong>Nivel</strong> <strong>de</strong><br />

Múltiples <strong>Fila</strong>s<br />

3-4 Copyright © Oracle Corporation, 1998. All rights reserved.


<strong>Funciones</strong> a <strong>Nivel</strong> <strong>de</strong> <strong>Fila</strong>: Sintaxis<br />

• Manipulan ítems <strong>de</strong> datos.<br />

• Aceptan argumentos y <strong>de</strong>vuelven un valor.<br />

• Actúan sobre cada fila retornada.<br />

• Devuelven un resultado por fila.<br />

• Modifican el tipo <strong>de</strong> datos.<br />

• Pue<strong>de</strong>n estar anidadas.<br />

Sintaxis:<br />

function_name (column|expression, [arg1, arg2,...])<br />

3-5 Copyright © Oracle Corporation, 1998. All rights reserved.


<strong>Funciones</strong> a <strong>Nivel</strong> <strong>de</strong> <strong>Fila</strong><br />

Character<br />

General<br />

Single-row<br />

functions<br />

Number<br />

Conversion<br />

Date<br />

3-6 Copyright © Oracle Corporation, 1998. All rights reserved.


<strong>Funciones</strong> <strong>de</strong> Caracteres<br />

<strong>Funciones</strong> <strong>de</strong><br />

Caracteres<br />

<strong>Funciones</strong> <strong>de</strong> Conversión<br />

LOWER<br />

UPPER<br />

INITCAP<br />

<strong>Funciones</strong> <strong>de</strong><br />

Manipulación <strong>de</strong> Caracteres<br />

CONCAT<br />

SUBSTR<br />

LENGTH<br />

INSTR<br />

LPAD<br />

3-7 Copyright © Oracle Corporation, 1998. All rights reserved.


<strong>Funciones</strong> <strong>de</strong> Conversión<br />

Conversión <strong>de</strong> ca<strong>de</strong>nas <strong>de</strong> caracteres<br />

Función<br />

LOWER('Curso SQL')<br />

UPPER ('Curso SQL')<br />

INITCAP('Curso SQL')<br />

Resultado<br />

curso sql<br />

CURSO SQL<br />

Curso Sql<br />

3-8 Copyright © Oracle Corporation, 1998. All rights reserved.


Uso <strong>de</strong> <strong>Funciones</strong> <strong>de</strong> Conversión<br />

Visualizar el número <strong>de</strong> empleado,<br />

nombre y nº <strong>de</strong> <strong>de</strong>partamento <strong>de</strong> “Blake”.<br />

SQL> SELECT empno, ename, <strong>de</strong>ptno<br />

2 FROM emp<br />

3 WHERE ename = 'blake';<br />

no rows selected<br />

SQL> SELECT empno, ename, <strong>de</strong>ptno<br />

2 FROM emp<br />

3 WHERE LOWER(ename) = 'blake';<br />

EMPNO ENAME<br />

DEPTNO<br />

--------- ---------- ---------<br />

7698 BLAKE 30<br />

3-9 Copyright © Oracle Corporation, 1998. All rights reserved.


<strong>Funciones</strong> <strong>de</strong> Manipulación <strong>de</strong><br />

Caracteres<br />

Manipulación <strong>de</strong> ca<strong>de</strong>nas <strong>de</strong> caracteres<br />

Función<br />

CONCAT('Good', 'String')<br />

SUBSTR('String',1,3)<br />

LENGTH('String')<br />

INSTR('String', 'r')<br />

LPAD(sal,10,'*')<br />

Resultado<br />

GoodString<br />

Str<br />

6<br />

3<br />

******5000<br />

3-10 Copyright © Oracle Corporation, 1998. All rights reserved.


Uso <strong>de</strong> <strong>Funciones</strong> <strong>de</strong> Manipulación <strong>de</strong><br />

Caracteres<br />

SQL> SELECT ename, CONCAT (ename, job), LENGTH(ename),<br />

2 INSTR(ename, 'A')<br />

3 FROM emp<br />

4 WHERE SUBSTR(job,1,5) = 'SALES';<br />

ENAME CONCAT(ENAME,JOB) LENGTH(ENAME) INSTR(ENAME,'A')<br />

---------- ------------------- ------------- ----------------<br />

MARTIN MARTINSALESMAN 6 2<br />

ALLEN ALLENSALESMAN 5 1<br />

TURNER TURNERSALESMAN 6 0<br />

WARD WARDSALESMAN 4 2<br />

3-11 Copyright © Oracle Corporation, 1998. All rights reserved.


• ROUND:<br />

<strong>Funciones</strong> Numéricas<br />

Redon<strong>de</strong>a un valor al <strong>de</strong>cimal<br />

especificado<br />

ROUND(45.926, 2) 45.93<br />

• TRUNC:<br />

Trunca un valor en el <strong>de</strong>cimal<br />

especificado<br />

TRUNC(45.926, 2) 45.92<br />

• MOD:<br />

Devuelve el resto <strong>de</strong> la división<br />

MOD(1600, 300) 100<br />

3-12 Copyright © Oracle Corporation, 1998. All rights reserved.


Uso <strong>de</strong> la Función ROUND<br />

Visualizar el valor 45.923 redon<strong>de</strong>ado a<br />

centenas, 0, y 10 posiciones <strong>de</strong>cimales.<br />

SQL> SELECT ROUND(45.923,2), ROUND(45.923,0),<br />

2 ROUND(45.923,-1)<br />

3 FROM SYS.DUAL;<br />

ROUND(45.923,2) ROUND(45.923,0) ROUND(45.923,-1)<br />

--------------- -------------- -----------------<br />

45.92 46 50<br />

3-13 Copyright © Oracle Corporation, 1998. All rights reserved.


Uso <strong>de</strong> la Función TRUNC<br />

Visualizar el valor 45.923 con TRUNC a<br />

centenas, 0, y 10 posiciones <strong>de</strong>cimales.<br />

SQL> SELECT TRUNC(45.923,2), TRUNC(45.923),<br />

2 TRUNC(45.923,-1)<br />

3 FROM SYS.DUAL;<br />

TRUNC(45.923,2) TRUNC(45.923) TRUNC(45.923,-1)<br />

--------------- ------------- ---------------<br />

45.92 45 40<br />

3-14 Copyright © Oracle Corporation, 1998. All rights reserved.


Uso <strong>de</strong> la Función MOD<br />

Calcular el resto <strong>de</strong> dividir el salario entre<br />

la comisión <strong>de</strong> cada empleado, cuyo<br />

trabajo sea “VENDEDOR”.<br />

SQL> SELECT ename, sal, comm, MOD(sal, comm)<br />

2 FROM emp<br />

3 WHERE job = 'SALESMAN';<br />

ENAME SAL COMM MOD(SAL,COMM)<br />

---------- --------- --------- -------------<br />

MARTIN 1250 1400 1250<br />

ALLEN 1600 300 100<br />

TURNER 1500 0 1500<br />

WARD 1250 500 250<br />

3-15 Copyright © Oracle Corporation, 1998. All rights reserved.


Trabajando con Fechas<br />

• Oracle almacena fechas en un formato numérico<br />

interno.<br />

– Siglo, año, mes, día, horas, minutos,<br />

segundos.<br />

• El formato <strong>de</strong> fecha por <strong>de</strong>fecto es DD-MON-YY.<br />

• SYSDATE es una función que <strong>de</strong>vuelve fecha y<br />

hora.<br />

• DUAL es una tabla virtual <strong>de</strong> la Base <strong>de</strong> Datos,<br />

que pue<strong>de</strong> ser usada para inspeccionar<br />

SYSDATE.<br />

3-16 Copyright © Oracle Corporation, 1998. All rights reserved.


Operadores Aritméticos <strong>de</strong> Fechas<br />

• Sumar o restar un número a ó <strong>de</strong> una<br />

fecha da por resultado una fecha.<br />

• Restar dos fechas para encontrar la<br />

cantidad <strong>de</strong> días entre esas fechas.<br />

• Sumar horas a una fecha dividiendo la<br />

cantidad <strong>de</strong> horas por 24.<br />

3-17 Copyright © Oracle Corporation, 1998. All rights reserved.


Uso <strong>de</strong> Operadores Aritméticos en<br />

Fechas<br />

SQL> SELECT ename, (SYSDATE-hiredate)/7 WEEKS<br />

2 FROM emp<br />

3 WHERE <strong>de</strong>ptno = 10;<br />

ENAME<br />

WEEKS<br />

---------- ---------<br />

KING 830.93709<br />

CLARK 853.93709<br />

MILLER 821.36566<br />

3-18 Copyright © Oracle Corporation, 1998. All rights reserved.


<strong>Funciones</strong> <strong>de</strong> Fecha<br />

FUNCION<br />

MONTHS_BETWEEN<br />

ADD_MONTHS<br />

NEXT_DAY<br />

LAST_DAY<br />

ROUND<br />

TRUNC<br />

DESCRIPCION<br />

Número <strong>de</strong> meses entre dos<br />

fechas<br />

Agregar meses según<br />

calendario, a una fecha<br />

Próximo día <strong>de</strong> la fecha<br />

especificada<br />

Ultimo día <strong>de</strong>l mes<br />

Redon<strong>de</strong>a una fecha<br />

Trunca una fecha<br />

3-19 Copyright © Oracle Corporation, 1998. All rights reserved.


Uso <strong>de</strong> <strong>Funciones</strong> <strong>de</strong> Fecha<br />

• MONTHS_BETWEEN ('01-SEP-95','11-JAN-94')<br />

19.6774194<br />

• ADD_MONTHS ('11-JAN-94',6)<br />

'11-JUL-94'<br />

• NEXT_DAY ('01-SEP-95','FRIDAY')<br />

'08-SEP-95'<br />

• LAST_DAY('01-SEP-95')<br />

'30-SEP-95'<br />

3-20 Copyright © Oracle Corporation, 1998. All rights reserved.


Uso <strong>de</strong> <strong>Funciones</strong> <strong>de</strong> Fecha<br />

• ROUND('25-JUL-95','MONTH')<br />

01-AUG-95<br />

• ROUND('25-JUL-95','YEAR')<br />

01-JAN-96<br />

• TRUNC('25-JUL-95','MONTH')<br />

01-JUL-95<br />

• TRUNC('25-JUL-95','YEAR')<br />

01-JAN-95<br />

3-21 Copyright © Oracle Corporation, 1998. All rights reserved.


<strong>Funciones</strong> <strong>de</strong> Conversión<br />

Conversión <strong>de</strong><br />

Tipos <strong>de</strong> Datos<br />

Conversión<br />

Implícita<br />

Conversión<br />

Explícita<br />

3-22 Copyright © Oracle Corporation, 1998. All rights reserved.


Conversión Implícita <strong>de</strong>l Tipo <strong>de</strong> Dato<br />

Para asignaciones, Oracle automáticamente<br />

pue<strong>de</strong> convertir:<br />

De<br />

VARCHAR2 o CHAR<br />

VARCHAR2 o CHAR<br />

NUMBER<br />

DATE<br />

A<br />

NUMBER<br />

DATE<br />

VARCHAR2<br />

VARCHAR2<br />

3-23 Copyright © Oracle Corporation, 1998. All rights reserved.


Conversión Explícita <strong>de</strong>l Tipo <strong>de</strong> Dato<br />

Para evaluar una expresión, Oracle<br />

automáticamente pue<strong>de</strong> convertir:<br />

De<br />

A<br />

VARCHAR2 o CHAR<br />

VARCHAR2 o CHAR<br />

NUMBER<br />

DATE<br />

3-24 Copyright © Oracle Corporation, 1998. All rights reserved.


Conversión Explícita <strong>de</strong>l Tipo <strong>de</strong> Dato<br />

TO_NUMBER<br />

TO_DATE<br />

NUMBER<br />

CHARACTER<br />

DATE<br />

TO_CHAR<br />

TO_CHAR<br />

3-25 Copyright © Oracle Corporation, 1998. All rights reserved.


Función TO_CHAR con Fechas<br />

TO_CHAR(date, 'fmt')<br />

El formato:<br />

• Debe estar encerrado entre comillas simples y<br />

es sensible a mayúsculas/minúsculas.<br />

• Pue<strong>de</strong> incluir cualquier elemento <strong>de</strong> formato<br />

<strong>de</strong> fecha válido.<br />

• Tiene un elemento fm (fill mo<strong>de</strong>) para eliminar<br />

espacios en blanco <strong>de</strong> relleno o suprimir ceros<br />

a la izquierda.<br />

• Está separado <strong>de</strong> la fecha por una coma.<br />

3-26 Copyright © Oracle Corporation, 1998. All rights reserved.


Elementos <strong>de</strong>l Mo<strong>de</strong>lo Formato <strong>de</strong> Fecha<br />

YYYY<br />

YEAR<br />

MM<br />

MONTH<br />

DY<br />

DAY<br />

Año completo en número<br />

Año en letras<br />

Nº <strong>de</strong>l mes con dos dígitos<br />

Nombre completo <strong>de</strong>l mes<br />

Abreviatura <strong>de</strong> tres letras <strong>de</strong>l<br />

día <strong>de</strong> la semana<br />

Nombre completo <strong>de</strong>l día<br />

3-27 Copyright © Oracle Corporation, 1998. All rights reserved.


Elementos <strong>de</strong>l Formato <strong>de</strong> Fechas<br />

• Obtención <strong>de</strong> la hora:<br />

HH24:MI:SS AM<br />

15:45:32 PM<br />

• Añadir ca<strong>de</strong>nas <strong>de</strong> caracteres encerrándolas<br />

entre dobles comillas.<br />

DD "of" MONTH 12 of OCTOBER<br />

• Sufijo que permita obtener el nº <strong>de</strong>l día en letra.<br />

ddspth<br />

fourteenth<br />

3-28 Copyright © Oracle Corporation, 1998. All rights reserved.


Formato <strong>de</strong> Fecha RR<br />

Año Actual<br />

1995<br />

1995<br />

2001<br />

2001<br />

Fecha Específicada<br />

27-OCT-95<br />

27-OCT-17<br />

27-OCT-17<br />

27-OCT-95<br />

Formato RR<br />

1995<br />

2017<br />

2017<br />

1995<br />

FormatoYY<br />

1995<br />

1917<br />

2017<br />

2095<br />

Si los 2<br />

dígitos <strong>de</strong>l<br />

año<br />

corriente<br />

están<br />

0-49<br />

50-99<br />

Si los 2 dígitos especificados <strong>de</strong>l año están<br />

0-49 50-99<br />

La fecha <strong>de</strong>vuelta<br />

correspon<strong>de</strong> al<br />

siglo corriente.<br />

La fecha <strong>de</strong>vuelta<br />

correspon<strong>de</strong> al<br />

siglo posterior al<br />

corriente.<br />

La fecha <strong>de</strong>vuelta<br />

correspon<strong>de</strong> al siglo<br />

anterior al corriente.<br />

La fecha <strong>de</strong>vuelta<br />

correspon<strong>de</strong> al siglo<br />

corriente.<br />

3-29 Copyright © Oracle Corporation, 1998. All rights reserved.


Función TO_CHAR con Fechas<br />

SQL> SELECT ename,<br />

2 TO CHAR(hiredate, 'fmDD Month YYYY') HIREDATE<br />

3 FROM emp;<br />

ENAME HIREDATE<br />

---------- -----------------<br />

KING 17 November 1981<br />

BLAKE 1 May 1981<br />

CLARK 9 June 1981<br />

JONES 2 April 1981<br />

MARTIN 28 September 1981<br />

ALLEN 20 February 1981<br />

...<br />

14 rows selected.<br />

3-30 Copyright © Oracle Corporation, 1998. All rights reserved.


Función TO_CHAR con Números<br />

TO_CHAR(number, 'fmt')<br />

Use estos formatos con la función<br />

TO_CHAR para mostrar un carácter como<br />

un número.<br />

9<br />

0<br />

$<br />

L<br />

.<br />

,<br />

Representa un número<br />

Fuerza a que se muestre el 0 (cero)<br />

Signo <strong>de</strong>l dólar<br />

Usa el símbolo <strong>de</strong> moneda local<br />

Imprime el punto <strong>de</strong>cimal<br />

Imprime el indicador <strong>de</strong> millar<br />

3-31 Copyright © Oracle Corporation, 1998. All rights reserved.


Uso <strong>de</strong> la<br />

Función TO_CHAR con Números<br />

SQL> SELECT TO_CHAR(sal,'$99,999') SALARY<br />

2 FROM emp<br />

3 WHERE ename = 'SCOTT';<br />

SALARY<br />

--------<br />

$3,000<br />

3-32 Copyright © Oracle Corporation, 1998. All rights reserved.


<strong>Funciones</strong><br />

TO_NUMBER y TO_DATE<br />

• Convierte una ca<strong>de</strong>na <strong>de</strong> caracteres a<br />

un formato numérico usando la función<br />

TO_NUMBER<br />

TO_NUMBER(char)<br />

• Convierte una ca<strong>de</strong>na <strong>de</strong> caracteres a<br />

un formato <strong>de</strong> fecha usando la función<br />

TO_DATE<br />

TO_DATE(char[, 'fmt'])<br />

3-33 Copyright © Oracle Corporation, 1998. All rights reserved.


NVL Function<br />

Convierte un nulo a un valor.<br />

• Los tipos <strong>de</strong> datos pue<strong>de</strong>n ser <strong>de</strong> fecha,<br />

ca<strong>de</strong>nas <strong>de</strong> caracteres y números.<br />

• Los tipos <strong>de</strong> datos <strong>de</strong>ben coincidir:<br />

– NVL(comm,0)<br />

– NVL(hiredate,'01-JAN-97')<br />

– NVL(job,'No Job Yet')<br />

3-34 Copyright © Oracle Corporation, 1998. All rights reserved.


Uso <strong>de</strong> la Función NVL<br />

SQL> SELECT ename, sal, comm, (sal*12)+NVL(comm,0)<br />

2 FROM emp;<br />

ENAME SAL COMM (SAL*12)+NVL(COMM,0)<br />

---------- --------- --------- --------------------<br />

KING 5000 60000<br />

BLAKE 2850 34200<br />

CLARK 2450 29400<br />

JONES 2975 35700<br />

MARTIN 1250 1400 16400<br />

ALLEN 1600 300 19500<br />

...<br />

14 rows selected.<br />

3-35 Copyright © Oracle Corporation, 1998. All rights reserved.


La Función DECODE<br />

Hace las veces <strong>de</strong> sentecias CASE o<br />

IF-THEN-ELSE, para facilitar consultas<br />

condicionales.<br />

DECODE(col/expression, search1, result1<br />

[, search2, result2,...,]<br />

[, <strong>de</strong>fault])<br />

3-36 Copyright © Oracle Corporation, 1998. All rights reserved.


Uso <strong>de</strong> la Función DECODE<br />

SQL> SELECT job, sal,<br />

2 DECODE(job, 'ANALYST' SAL*1.1,<br />

3 'CLERK', SAL*1.15,<br />

4 'MANAGER', SAL*1.20,<br />

5 SAL)<br />

6 REVISED_SALARY<br />

7 FROM emp;<br />

JOB<br />

SAL REVISED_SALARY<br />

--------- --------- --------------<br />

PRESIDENT 5000 5000<br />

MANAGER 2850 3420<br />

MANAGER 2450 2940<br />

...<br />

14 rows selected.<br />

3-37 Copyright © Oracle Corporation, 1998. All rights reserved.


Anudamiento <strong>de</strong> <strong>Funciones</strong><br />

• Las funciones a nivel <strong>de</strong> fila pue<strong>de</strong>n ser<br />

anidadas hasta cualquier nivel.<br />

• Las funciones anidadas son evaluadas <strong>de</strong>s<strong>de</strong><br />

el nivel más profundo al nivel menos<br />

profundo.<br />

F3(F2(F1(col,arg1),arg2),arg3)<br />

Paso 1 = Resultado 1!<br />

Paso 2 = Resultado 2!<br />

Paso 3 = Resultado 3!<br />

3-38 Copyright © Oracle Corporation, 1998. All rights reserved.


<strong>Funciones</strong> Anidadas<br />

SQL> SELECT ename,<br />

2 NVL(TO_CHAR(mgr),'No Manager')<br />

3 FROM emp<br />

4 WHERE mgr IS NULL;<br />

ENAME NVL(TO_CHAR(MGR),'NOMANAGER')<br />

---------- -----------------------------<br />

KING No Manager<br />

3-39 Copyright © Oracle Corporation, 1998. All rights reserved.


Resumen<br />

Use funciones para:<br />

• Realizar cáculos sobre los datos<br />

• Modificar datos <strong>de</strong> forma individual<br />

• Manipular la salida <strong>de</strong> grupos <strong>de</strong><br />

registros<br />

• Alterar formatos <strong>de</strong> fecha en su<br />

visualización<br />

• Convertir tipos <strong>de</strong> datos <strong>de</strong> columnas<br />

3-40 Copyright © Oracle Corporation, 1998. All rights reserved.


Visión General <strong>de</strong> la Práctica<br />

• Crear consultas que requieran el uso <strong>de</strong><br />

funciones numéricas, <strong>de</strong> caracteres y <strong>de</strong><br />

fechas.<br />

• Usar concatenación con funciones.<br />

• Escribir consultas case insensitive para probar<br />

la utilidad <strong>de</strong> las funciones <strong>de</strong> caracteres.<br />

• Ejecutar cálculos sobre años y meses <strong>de</strong><br />

servicio para un empleado.<br />

• Determinar la fecha <strong>de</strong> revisión para un<br />

empleado.<br />

3-41 Copyright © Oracle Corporation, 1998. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!