12.07.2015 Views

Loop FOR

Loop FOR

Loop FOR

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

6Creación de Estructuras deControlCopyright © Oracle Corporation, 1998. All rights reserved.


ObjetivosAl final de esta lección n será capaz de:• Identificar los usos y tipos de lasestructuras de control• Generar una sentencia IF• Generar e identificar distintassentencias de bucle• Utilizar tablas lógicas• Controlar el flujo de bloques utilizandoetiquetas y bucles anidados6-2 Copyright © Oracle Corporation, 1998. All rights reserved.


Control del Flujo de EjecuciónPL/SQLPuede modificar el flujo lógico ldesentencias utilizando sentencias IFcondicionales y estructuras de control debucles.• Sentencias IF condicionales:– IF-THEN– IF-THEN-ELSE– IF-THEN-ELSIF6-3 Copyright © Oracle Corporation, 1998. All rights reserved.


SintaxisIF IF condition THENstatements;[ELSIF condition THENstatements;][ELSEstatements;]END IF;Sentencia IF Simple:Sentencias IFEstablezca el ID del gestor en 22 si elombre del empleado es Osborne.IF IF v_ename = 'OSBORNE' THENv_mgr := := 22;END IF;6-4 Copyright © Oracle Corporation, 1998. All rights reserved.


Sentencias IF SimplesEstablezca el título ttulo de empleo enVendedor, el número nde departamento en35 y la comisión n en el 20% del salarioactual si el apellido es Miller.Ejemplo. . .IF IF v_ename = 'MILLER' THENv_job := := 'SALESMAN';v_deptno := := 35;v_new_comm := := sal * 0.20;END IF;. . .6-5 Copyright © Oracle Corporation, 1998. All rights reserved.


Flujo de Ejecución de laSentencia IF-THEN-ELSETRUECondición n IFFALSEAcciones THEN(incluyendo otros IFs)Acciones ELSE(incluyendo otros IFs)6-6 Copyright © Oracle Corporation, 1998. All rights reserved.


Sentencias IF-THEN-ELSEEstablezca un indicador para los pedidosen los que hay menos de 5 días dentre lafecha de pedido y la fecha de envío.Ejemplo...IF IF v_shipdate - v_orderdate < 5 THENv_ship_flag := := 'Acceptable';ELSEv_ship_flag := := 'Unacceptable';END IF;...6-7 Copyright © Oracle Corporation, 1998. All rights reserved.


Sentencias IF-THEN-ELSIFPara un valor introducido concreto,devuelva un valor calculado.Ejemplo. . .IF IF v_start > 100 THENRETURN (2 (2 * v_start);ELSIF v_start >= >= 50 50 THENRETURN (.5 * v_start);ELSERETURN (.1 * v_start);END IF;. . .6-8 Copyright © Oracle Corporation, 1998. All rights reserved.


Flujo de Ejecución de laSentencia IF-THEN-ELSIFTRUECondición n IFIFFALSEAcciones THENTRUECondiciónELSIFFALSEAcciones THENAccionesELSE6-9 Copyright © Oracle Corporation, 1998. All rights reserved.


Generación de CondicionesLógicas• Puede manejar los valores nulos con eloperador IS NULL.• Las expresiones que contienen un valornulo resultan en NULL.• Las expresiones concatenadas convalores nulos tranta los valores nuloscomo a una cadena vacía.6-10 Copyright © Oracle Corporation, 1998. All rights reserved.


Tablas LógicasGenere una simple condición n booleanacon un operador de comparación.ANDTRUE FALSE NULLORTRUE FALSE NULLNOTTRUETRUEFALSENULLTRUETRUETRUETRUETRUEFALSEFALSEFALSEFALSEFALSEFALSETRUEFALSENULLFALSETRUENULLNULLFALSENULLNULLTRUENULLNULLNULLNULL6-11 Copyright © Oracle Corporation, 1998. All rights reserved.


Condiciones Booleanas¿Cuál l es el valor de V_FLAG en cadacaso?v_flag := := v_reorder_flag AND v_available_flag;V_REORDER_FLAG V_AVAILABLE_FLAG V_FLAGTRUETRUENULLNULLTRUEFALSETRUEFALSETRUEFALSENULLFALSE6-12 Copyright © Oracle Corporation, 1998. All rights reserved.


Control iterativo: SentenciasLOOP• Los bucles repiten una sentencia o unasecuencia de sentencias varias veces.• Hay tres tipos de bucles:– Bucle básico– Bucle <strong>FOR</strong>– Bucle WHILE6-13 Copyright © Oracle Corporation, 1998. All rights reserved.


Bucle BásicoSintaxisLOOPstatement1;. . .EXIT [WHEN condition];END LOOP;-- delimiter-- statements-- EXIT statement-- delimiterdonde: condition es es una expresión o variablebooleana (TRUE, FALSE,oNULL);6-14 Copyright © Oracle Corporation, 1998. All rights reserved.


EjemploBucle Básico. . .v_ordid item.ordid%TYPE := := 101;v_counter NUMBER(2) := := 1; 1;BEGIN. . .LOOPINSERT INTO item(ordid, itemid)VALUES(v_ordid, v_counter);v_counter := := v_counter + 1; 1;EXIT WHEN v_counter > 10;END LOOP;. . .6-15 Copyright © Oracle Corporation, 1998. All rights reserved.


SintaxisBucle <strong>FOR</strong><strong>FOR</strong> index in in [REVERSE]lower_bound..upper_bound LOOPstatement1;statement2;. . .END LOOP;• Utilice un bucle <strong>FOR</strong> para reducir elnúmero de repeticiones.• No declare el índice; se declaraimplícitamente.6-16 Copyright © Oracle Corporation, 1998. All rights reserved.


DirectricesBucle <strong>FOR</strong>• Haga referencia únicamente al índice queestá dentro del bucle; fuera del bucle noestá definido.• Utilice una expresión para hacerreferencia al valor existente de un índice.• No haga referencia al índice como objetivode una asignación.6-17 Copyright © Oracle Corporation, 1998. All rights reserved.


Bucle <strong>FOR</strong>Inserte los 10 primeros artículos nuevos delíena del pedido número n101.Ejemplo. . .v_ordid item.ordid%TYPE := := 101;BEGIN. . .<strong>FOR</strong> i IN IN 1..10 LOOPINSERT INTO item(ordid, itemid)VALUES(v_ordid, i);END LOOP;. . .6-18 Copyright © Oracle Corporation, 1998. All rights reserved.


Bucle WHILESintaxisWHILE condition LOOPstatement1;statement2;. . .END LOOP;Condition isevaluated at thebeginning ofeach iteration.Utilice el bucle WHILE para repetirsentencias mientras haya una condiciónTRUE6-19 Copyright © Oracle Corporation, 1998. All rights reserved.


Ejemplo<strong>Loop</strong> WHILEACCEPT p_price PROMPT ‘Enter the price of of the item: ‘ACCEPT p_itemtot PROMPT ‘Enter the maximum total forpurchase of of item: ‘DECLARE...v_qty NUMBER(8) := := 1; 1;v_running_total NUMBER(7,2) := := 0; 0;BEGIN...WHILE v_running_total < &p_itemtot LOOP...v_qty := := v_qty + 1; 1;v_running_total := := v_qty * p_price;END LOOP;...6-20 Copyright © Oracle Corporation, 1998. All rights reserved.


Etiquetas y <strong>Loop</strong>s Anidados• Anide bucles a varios niveles.• Utilice etiquetas para distinguir entrelos bloques y los bucles.• Salga del bucle externo con la sentenciaEXIT que hace referencia a la etiqueta.6-21 Copyright © Oracle Corporation, 1998. All rights reserved.


Etiquetas y <strong>Loop</strong>s Anidados...BEGINLOOPv_counter :=v_counter+1;EXIT WHEN v_counter>10;LOOP...EXIT Outer_loop WHEN total_done = 'YES';-- -- Leave both loopsEXIT WHEN inner_done = 'YES';-- -- Leave inner loop only...END LOOP Inner_loop;...END LOOP Outer_loop;END;6-22 Copyright © Oracle Corporation, 1998. All rights reserved.


ResumenCambie el flujo lógico lde sentenciautilizando estructuras de control.• Condicional (sentencia IF)– IF THEN– IF-THEN-ELSE– IF-THEN-ELSIF6-23 Copyright © Oracle Corporation, 1998. All rights reserved.


• <strong>Loop</strong>s– <strong>Loop</strong> básico– <strong>Loop</strong> <strong>FOR</strong>– <strong>Loop</strong> WHILE– Sentencia EXITResumen6-24 Copyright © Oracle Corporation, 1998. All rights reserved.


Visión General de la Práctica• Ejecución de acciones condicionalesutilizando la sentencia IF• Ejecución de iteraciones utilizando laestructura bucle6-25 Copyright © Oracle Corporation, 1998. All rights reserved.

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

Saved successfully!

Ooh no, something went wrong!