domingo, 14 de octubre de 2007

Cursores PL/SQL notación SELECT..INTO..EXCEPTION

Creamos dos procedimientos que ejecutan la misma sentencia SQL, recuperan las mismas filas y las muestran en pantalla. El primero NO gestiona las excepciones y muestra errores en pantalla. El segundo gestiona las excepciones y no deja que se vean errores en pantalla. Comparamos los funcionamientos.
El procedimiento sin gestión de excepciones se llama SELECT_INTO_SIN_EXCEPTION. Selecciona una fila y muestra el valor que contiene una columna de la fila seleccionada. Utilizamos para selecionar la fila el Parametro_Nombre que nos permite ejecutar la lógica o programa trabajando con distintas filas en cada ejecución.
SQL> CONNECT FERNANDEZ/FERNANDEZ
Conectado.

SQL> SET SERVEROUTPUT ON

SQL> create or replace
2 PROCEDURE SELECT_INTO_SIN_EXCEPTION(Parametro_Nombre IN ALL_VIEWS.VIEW_NAME%TYPE)
3 AS
4 vTEXT_LENGTH ALL_VIEWS.TEXT_LENGTH%TYPE;
5 BEGIN
6 SELECT TEXT_LENGTH
7 INTO vTEXT_LENGTH
8 FROM SYS.ALL_VIEWS
9 WHERE OWNER = 'SYS'
10 AND VIEW_NAME LIKE Parametro_Nombre;
11
12 DBMS_OUTPUT.PUT_LINE('La longitud del texto de la vista es:');
13 DBMS_OUTPUT.PUT_LINE(vTEXT_LENGTH);
14 END SELECT_INTO_SIN_EXCEPTION;
15 /

Procedimiento creado.
Verificamos la existencia del procedimiento con el comando DESCRIBE. Vemos que no solo se muestra el nombre del procedimiento SELECT_INTO_SIN_EXCEPTION sino que también se detalla el nombre del parámetro PARAMETRO_NOMBRE que es sólo de entrada de datos (E/S=IN).
SQL> DESC SELECT_INTO_SIN_EXCEPTION;
PROCEDURE SELECT_INTO_SIN_EXCEPTION
Nombre de Argumento Tipo E/S ┐Por Defecto?
------------------------------ ----------------------- ------ --------
PARAMETRO_NOMBRE VARCHAR2(30) IN

Ejecutamos el procedimiento pasando por parámetro el valor 'USER_TABLES'. Sólo una fila de ALL_VIEWS evalúa verdadera la condición de la cláusula WHERE VIEW_NAME LIKE 'USER_TABLES'. Se recupera la fila y se muestra en pantalla el valor de la columna TEXT_LENGTH de dicha fila.
SQL> EXECUTE SELECT_INTO_SIN_EXCEPTION('USER_TABLES');
La longitud del texto de la vista es:
3971


Procedimiento PL/SQL terminado correctamente.

SQL>
Ejecutamos el procedimiento pasando por parámetro el valor 'NOMBRE_INEXISTENTE'. No existe ninguna fila con dicho nombre en ALL_VIEWS por lo tanto se levanta la excepción "ORA-01403: No se ha encontrado ningún dato" ("ORA-01403: no data found"). El procedimiento no posee instrucciones para atrapar, capturar ni gestionar esta excepción por lo tanto se propaga haca el nivel superior. El SQL*Plus es el proceso ejecutor del procedimiento, recibe la excepción levantada por el procedimiento y muestra el mensaje asociado a la excepción en la pantalla.
SQL> EXECUTE SELECT_INTO_SIN_EXCEPTION('NOMBRE_INEXISTENTE');
BEGIN SELECT_INTO_SIN_EXCEPTION('NOMBRE_INEXISTENTE'); END;

*
ERROR en línea 1:
ORA-01403: No se ha encontrado ningún dato
ORA-06512: en "FERNANDEZ.SELECT_INTO_SIN_EXCEPTION", línea 5
ORA-06512: en línea 1
Ejecutamos el procedimiento pasando por parámetro el valor comodín '%'. Todas las filas comparadas con el comodín '%' evalúan la condición con el valor verdadero por lo tanto se recuperan todas las filas de ALL_VIEWS. El procedimiento ejecuta la sentencia con la notación SELECT..INTO.. contemplanto sólo la recuperación de una única fila. Como no tiene soporte para la recuperación de múltiples filas, se levanta la excepción "ORA-01403: No se ha encontrado ningún dato" ("ORA-01403: no data found"). El procedimiento no posee instrucciones para atrapar, capturar ni gestionar esta excepción por lo tanto se propaga haca el nivel superior. El SQL*Plus es el proceso ejecutor del procedimiento, recibe la excepción levantada por el procedimiento y muestra el mensaje asociado a la excepción en la pantalla.
SQL> EXECUTE SELECT_INTO_SIN_EXCEPTION('%');
BEGIN SELECT_INTO_SIN_EXCEPTION('%'); END;

*
ERROR en línea 1:
ORA-01422: la recuperación exacta devuelve un número mayor de filas que el solicitado
ORA-06512: en "FERNANDEZ.SELECT_INTO_SIN_EXCEPTION", línea 5
ORA-06512: en línea 1
Creamos el procedimiento SELECT_INTO_CON_EXCEPTION similar al procedimiento SELECT_INTO_SIN_EXCEPTION con el agregado del manejo de excepciones de error:
Línea 15: Inicio del bloque de gestión de excepciones.
Líneas 16 a 17: Definimos qué debe hacer el procedimiento sin entre el BEGIN y el EXCEPTION se levanta un error de excepción del tipo NO_DATA_FOUND, es decir, "ORA-01403: No se ha encontrado ningún dato". Se muestra el texto DATOS BUSCADOS NO ENCONTRADOS! y no se propaga el error al nivel superior.
Líneas 18 a 19: Si se leventa la excepción TOO_MANY_ROWS, es decir, "ORA-01422: la recuperación exacta devuelve un número mayor de filas que el solicitado" ("ORA-01422: exact fetch returns more than requested number of rows") se muestra en pantalla el mensaje SE ENCONTRO MAS DE UNA FILA! y no se propaga el error al nivel superior.

SQL> create or replace
2 PROCEDURE SELECT_INTO_CON_EXCEPTION(Parametro_Nombre IN ALL_VIEWS.VIEW_NAM
E%TYPE)
3 AS
4 vTEXT_LENGTH ALL_VIEWS.TEXT_LENGTH%TYPE;
5 BEGIN
6 SELECT TEXT_LENGTH
7 INTO vTEXT_LENGTH
8 FROM SYS.ALL_VIEWS
9 WHERE OWNER = 'SYS'
10 AND VIEW_NAME LIKE Parametro_Nombre;
11
12 DBMS_OUTPUT.PUT_LINE('La longitud del texto de la vista es:');
13 DBMS_OUTPUT.PUT_LINE(vTEXT_LENGTH);
14
15 EXCEPTION
16 WHEN NO_DATA_FOUND THEN
17 DBMS_OUTPUT.PUT_LINE('DATOS BUSCADOS NO ENCONTRADOS!');
18 WHEN TOO_MANY_ROWS THEN
19 DBMS_OUTPUT.PUT_LINE('SE ENCONTRO MAS DE UNA FILA!');
20 END SELECT_INTO_CON_EXCEPTION;
21 /

Procedimiento creado.

SQL> DESCRIBE SELECT_INTO_CON_EXCEPTION
PROCEDURE SELECT_INTO_CON_EXCEPTION
Nombre de Argumento Tipo E/S ┐Por Defecto?
------------------------------ ----------------------- ------ --------
PARAMETRO_NOMBRE VARCHAR2(30) IN
Ejecutamos el procedimiento con los distintos valores de parámetros ejecutados anteriormente y vemos que no se muestran errores en pantalla. El manejo de excepciones las detecta y toma acciones específicas para cada una de ellas.
SQL> EXECUTE SELECT_INTO_CON_EXCEPTION('NOMBRE_INEXISTENTE');
DATOS BUSCADOS NO ENCONTRADOS!

Procedimiento PL/SQL terminado correctamente.

SQL> EXECUTE SELECT_INTO_CON_EXCEPTION('%');
SE ENCONTRO MAS DE UNA FILA!

Procedimiento PL/SQL terminado correctamente.

SQL> EXECUTE SELECT_INTO_CON_EXCEPTION('USER_TABLES');
La longitud del texto de la vista es:
3971


Procedimiento PL/SQL terminado correctamente.

11 comentarios:

Anónimo dijo...

Spot on with this write-up, I absolutely feel this web site needs far more attention.
I'll probably be back again to see more, thanks for the info!

my web blog does raspberry ketones work

Anónimo dijo...

Because the admin of this web page is working, no question very quickly it will be renowned, due to its feature
contents.

Also visit my blog :: responsive web design [http://ojfood.co.kr/xe/?document_srl=126129]

Anónimo dijo...

This info is worth everyone's attention. How can I find
out more?

Also visit my homepage :: goji actives realmente funciona

Anónimo dijo...

Its not my first time to pay a quick visit this site, i am
browsing this web page dailly and obtain nice data from here every day.


my blog ... cozumel mexico

Anónimo dijo...

Tell: A physical or verbal action, posture, move or look, which can let a observant player know
how strong or weak your hand is. For a $3-6 game, a pot
size in the range of $40-60 is a common qualifying amount.
If you don't have money, never name with the tiny blind.



my page - poker gratis online senza registrazione ()

Anónimo dijo...

Ϲlasses offer the oppоrtuitʏ to move to a bеat, incгease musicality and the use of the imagination. Both of them had been cast as
memƄers of "Duke Mantee's Gang" and so were dressed in their double-breasted, pin-striped suits,
fedora hats and black shіrts with white ties -- reрlete with "Tommy guns" made out of wood and painted black
by the Prop Dеpartment. Sharing the costs of
child-rearing needn't mean that you and the otheг parent must split exрenses at
exactly half and half.

Here is my web pɑge: Ballet Bible download

Anónimo dijo...

Pretty! This was a really wonderful article. Many thanks for providing this information.



Here is my site; indian rummy

Anónimo dijo...

This method is generally not adopted due to the large size of the tank required to hold the wastewater generated.

"Urban Environment and Heritage," Hyderabad City Development Plan. Finally the treated sludge may be superheated to kill the remaining pathogens and the result is used to manufacture fertilizer
pellets for farming.

My weblog milpolkorea.com ()

Anónimo dijo...

In this part of the pet provided on the phone. In game development because of the online casinos
open all download next car game day, every type of account,
do registrations or fill any survey! Have short, crisp content:
This platform is known for generating awesome 3D assets for games.

Anónimo dijo...

It's remarkable to pay a visit this web site and reading the views
of all mates about this paragraph, while I am also keen of getting experience.


Feel free to visit my blog post :: Frank Kern Tweeted This

Anónimo dijo...

I savor, result in I found exactly what I used to be looking for.
You've ended my four day lengthy hunt! God Bless you man. Have a nice day.
Bye

Here is my web site: Apartamenty w Juracie