Está en la página 1de 5

INDRA - Introduccion a PL/SQL

Practica1 - Variables Tipos de Datos


Ejercicio 1 ) Marcar la respuesta correcta
Ejemplo #1:
set serveroutput on;
set serveroutput on size 1000000;
declare
mi_var varchar(20):='hola mundo';
begin
dbms_output.put_line(mi_var);
sys.dbms_output.put_line('Fin del programa');
end;
/
a)

Devuelve

hola mundo
Fin del programa
b) Devuelve error de compilacin
Ejercicio 2 ) Marcar la respuesta correcta
Ejemplo #2
SET SERVEROUTPUT ON
DECLARE
V_NUM1 NUMBER(4,2):=10.2;
V_NUM2 NUMBER(4,2):=20.1;
BEGIN
DBMS_OUTPUT.PUT_LINE('LA SUMA ES: '||TO_CHAR(V_NUM1+V_NUM2));
END;
/
Devuelve
a)
b)
c)

LA SUMA ES: 30,3


No se pueden pasar a CHAR los NUM
No se puede inicializar en la seccion DECLARE, error de compilacion

Ejercicio 3 ) Marcar la respuesta correcta


SET SERVEROUTPUT ON
DECLARE
V_FECHA V$DATABASE.CREATED%TYPE;
BEGIN
SELECT CREATED INTO V_FECHA FROM V$DATABASE;
DBMS_OUTPUT.PUT_LINE('LA FECHA DE CREACION DE LA BASE DE DATOS
FUE: '||TO_CHAR(V_FECHA,'DDMMYYYY'));
END;
Devuelve
d)
e)

LA FECHA DE CREACION DE LA BASE DE DATOS fue 03042013


Error No se puede inicializar $DATABASE

Ejercicio4 ) CHAR

Crear un pl-sql que defina dos variables v_nombre_empleado_1 y v_nombre_empleado_2 con el nombre
Juan . La primera de tipo char de 6 y la segunda de tipo varchar de 6. Imprimir ambos valores
concatenando un * al principio .
1) Ocupan lo mismo ? Imprimir usando length(variable)
2) Asignar a v_nombre_empleado_1 el nombre Juan manuel Garcia
3) Asignar a v_nombre_empleado_1 el valor JG
4) Asignar a v_nombre_empleado_2 el valor JG
Ejercicio5 ) DATE
Objetivo: poder asignar ver que tipos de datos se pueden sumar entre, si. Dates , numbers.
Abrir el sql-developer y armar un pl-sql que cargue una fecha sysdate en una variable, arme la fecha de
fin de mes en otra variable, reste las fechas y calcule cuantos das faltan para fin de mes.
Imprimir la cantidad de das que faltan para fin de mes.
Referencias
1) http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/datatypes.htm#i45907

To find just the time portion of a DATE variable, subtract the date
portion:date_variable - TRUNC(date_variable).

Nota:
formatear la fecha
EXECUTE IMMEDIATE 'ALTER SESSION SET NLS_DATE_FORMAT = "dd-MON-yyyy" ';
Referencia funcin : TO_CHAR(date1 [,fmt]);

Fmt:
Parameter

Explanation

YEAR

Year, spelled out alphabetically

YYYY

4-digit year

YYY
YY
Y

Last 3, 2, or 1 digit(s) of year.

IYY
IY
I

Last 3, 2, or 1 digit(s) of ISO year.

IYYY

4-digit year based on the ISO standard

RRRR

Accepts a 2-digit year and returns a 4-digit year.


A value between 0-49 will return a 20xx year.
A value between 50-99 will return a 19xx year.

Quarter of year (1, 2, 3, 4; JAN-MAR = 1).

MM

Month (01-12; JAN = 01).

MON

Abbreviated name of the month.

MONTH

The name of month, padded with blanks to length of 9 characters.

RM

Roman numeral month (I-XII; JAN = I).

WW

The week of the year (1-53) where week 1 starts on the first day of
the year and continues to the seventh day of the year.

The week of the month (1-5) where week 1 starts on the first day of
the month and ends on the seventh.

IW

The week of year (1-52 or 1-53) based on the ISO standard.

Day of the week (1-7). Sunday is day 1 when nls_territory is set to


'AMERICA' but differs if another nls_territory is set (i.e. 'UNITED
KINGDOM' or 'GERMANY' - in these cases Monday is 1.

DAY

Name of the day.

DD

The day of month (1-31).

DDD

The day of year (1-366).

DY

Abbreviated name of the day. (Mon, Tue, Wed, etc)

Julian day; the number of days since January 1, 4712 BC.

HH

Hour of day (1-12).

HH12

Hour of day (1-12).

HH24

Hour of day (0-23).

MI

Minute (0-59).

SS

Second (0-59).

SSSSS

Number of seconds past midnight (0-86399).

FF

Fractional seconds. Use a value from 1 to 9 after FF to indicate the


number of digits in the fractional seconds. For example, 'FF5'.

AM, A.M., PM, or P.M. Meridian indicator


AD or A.D

AD indicator

BC or B.C.

BC indicator

TZD

Daylight savings identifier. For example, 'PST'

TZH

Time zone hour.

TZM

Time zone minute.

TZR

Time zone region.

Ejplo:
Este ejemplo pasa a date , formatea y luego pasa a char con otro formato
select TO_CHAR (TO_DATE('0297','MM/YY'), 'YY/MM') from dual

Ejercicio6 ) INSTR - SUBSTR


Objetivo: introducir las funciones de uso de cadenas
Crear un varchar2 con la siguiente cadena de caracteres : Ejemplo de uso de cadenas en pl/sql
3.a) Realizar un pl/sql que devuelva los primeros 10 caracteres. NOTA: controlar el caso de que el string
sea nulo. ( definir la variable como NOT NULL )
3.b) Realizar un pl/sql que solicite la cantidad de ultimos caracteres de la cadena. No controlar el caso de
que la cantidad sea mayor al tamao de la cadena.
3.c) Realizar un pl/sql que devuelva de la cadena enunciada cadenas en pl/sql. Es decir busque con
instr la segunda ocurrencia de la palabra de y luego desde ah hasta el final de la cadena con Substr
Referencias:
INSTR
http://www.techonthenet.com/oracle/functions/instr.php
INSTR( string, substring [, start_position [, nth_appearance ] ] )
string

The string to search. string can be CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or
NCLOB.
substring
The substring to search for in string. substring can be CHAR, VARCHAR2, NCHAR,
NVARCHAR2, CLOB, or NCLOB.
start_position
Optional. The position in string where the search will start. If omitted, it defaults to 1. The first
position in the string is 1. If the start_position is negative, the INSTR function counts
back start_position number of characters from the end of stringand then searches towards the
beginning of string.
nth_appearance
Optional. The nth appearance of substring. If omitted, it defaults to 1.
SUBSTR
SUBSTR( string, start_position [, length ] )

Parameters or Arguments
string
The source string.
start_position
The starting position for extraction. The first position in the string is always 1.
length
Optional. It is the number of characters to extract. If this parameter is omitted, the SUBSTR
function will return the entire string.
Note:

If start_position is 0, then the SUBSTR function treats start_position as 1 (ie: the first position in

the string).
If start_position is a positive number, then the SUBSTR function starts from the beginning of the

string.
If start_position is a negative number, then the SUBSTR function starts from the end of the string

and counts backwards.


If length is a negative number, then the SUBSTR function will return a NULL value.

Ejercicio 7 ) Precedencia de operadores


Realizar un pl/sql que tome la fecha del dia y le sume un segundo. Para ello tomar la fecha del dia una
variable y en otra variable asignarle el valor anterior dividido por 24*60*60. Verficar la predcedencia de la
division con la multiplicacin y la asignacin.
( Tener presente)
Table 21 Order of Operations
Operator Operation
**exponentiation
+, identity, negation
*, /multiplication, division
+, , ||addition, subtraction, concatenation
=, <, >, <=, >=, <>, !=, ~=, ^=,
ISNULL, LIKE, BETWEEN, IN
comparison
NOTlogical negation

ANDconjunction
ORinclusion

Ref: http://www.oracle.com/technetwork/issue-archive/2012/12-jan/o12plsql-1408561.html

Ejercicio 8) Clausulas adicionales. - RANGE


EL siguiente ejemplo define un rango de valores, ejecuta ?
DECLARE
digito
PLS_INTEGER RANGE 0..9;
dos_digitos PLS_INTEGER RANGE 10..99;
menos_de_100 PLS_INTEGER RANGE 0..99;
BEGIN
digito
:= 4;
dos_digitos := 35;
menos_de_100 := digito;
menos_de_100 := dos_digitos;
dos_digitos := digito;
END;
/

Ejercicio 9) NUMBER-TO_CHAR // TO_CHAR NUMBER - Conversiones implicitas


El dgito recuperado en el ejercicio 7, ingresarlo en una variable VARCHAR. Es posible ? Ver
conversiones implcitas en
http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/datatypes.htm#i42580

Ejercicio 10) Conversion de SIMPLE_INTEGER a BINARY

DECLARE
a SIMPLE_INTEGER := 1;
b PLS_INTEGER := NULL;
BEGIN
a := b;
END;
/
Ejercicio 11) Esto es correcto ?
DECLARE
acct_id INTEGER(4) NOT NULL ;
begin
DBMS_OUTPUT.PUT_LINE( acct_id ) ;
end;
/

También podría gustarte