En Oracle, For Loop es la forma más fácil de trabajar con Cursor. Abrirá el cursor, buscará y se cerrará solo. A continuación se muestran los ejemplos de cómo obtener datos de Cursor en Oracle usando For Loop.
Ejemplos de cursores de bucle For
1. Ejemplo de cursor sin parámetro
SET SERVEROUTPUT ON; DECLARE CURSOR c_emp IS SELECT * FROM emp; BEGIN FOR cur IN c_emp LOOP DBMS_OUTPUT.put_line ( 'Employee Name: ' || cur.ename || ' Job: ' || cur.job); END LOOP; END; /
Salida
Employee Name: SMITH Job: CLERK Employee Name: ALLEN Job: SALESMAN Employee Name: WARD Job: SALESMAN Employee Name: JONES Job: MANAGER Employee Name: MARTIN Job: SALESMAN Employee Name: BLAKE Job: MANAGER Employee Name: CLARK Job: MANAGER Employee Name: SCOTT Job: ANALYST Employee Name: KING Job: PRESIDENT Employee Name: TURNER Job: SALESMAN Employee Name: ADAMS Job: CLERK Employee Name: JAMES Job: CLERK Employee Name: FORD Job: ANALYST Employee Name: MILLER Job: CLERK PL/SQL procedure successfully completed.
2. Ejemplo de parametrización del cursor For Loop
SET SERVEROUTPUT ON; DECLARE CURSOR c_emp (p_job emp.job%type) IS SELECT * FROM emp where job = p_job; BEGIN FOR cur IN c_emp ('MANAGER') LOOP DBMS_OUTPUT.put_line ( 'Employee Name: ' || cur.ename || ' Job: ' || cur.job); END LOOP; END; /
Salida
Employee Name: JONES Job: MANAGER Employee Name: BLAKE Job: MANAGER Employee Name: CLARK Job: MANAGER PL/SQL procedure successfully completed.
Ver también:
- Ejemplo de recopilación masiva de Oracle con el cursor
- Siga recorriendo el cursor incluso si se produce un error
- Exportar datos a CSV en Oracle