Oracle/PL/SQL/Cursores
Los cursores permiten recorrer los registros que devuelve una consulta SQL.
También las operaciones INSERT, UPDATE Y DELETE definen un cursor implícito, denominado SQL.
Atributos de un cursor:
- %ROWCOUNT: Cantidad de registros
- %FOUND: Indica que hay datos (tipo boolean)
- %NOTFOUND: Indica que no hay datos (tipo boolean)
- %ISOPEN: Indica si el cursor está abierto (tipo boolean)
Ciclo FOR
[editar]declare
cursor public cur is
select col1, col2
from tabla;
begin
for v_reg in cur loop
dbms_output.put_line ('Col1: '|| v_reg.col1 ||' Col2: '|| v_reg.col2);
end loop;
end;
La variable v_reg se declara automáticamente y tiene validez únicamente dentro del ciclo FOR.
Es posible definir argumentos al declarar un cursor:
declare
v_col3 tabla.col3%type;
cursor cur (p_col3 col3%type) is
select col1, col2
from tabla
where col3 = p_col3;
begin
v_col3 := 7;
for v_reg in cur (v_col3) loop
dbms_output.put_line ('Col1: '|| v_reg.col1 ||' Col2: '|| v_reg.col2);
end loop;
end;
OPEN, FETCH y CLOSE
[editar]En ciertos casos, es necesario realizar el procesamiento del cursor paso a paso:
declare
cursor cur is
select col1, col2
from tabla;
v_reg cur%rowtype;
begin
open cur;
loop
fetch cur into v_reg;
exit when cur%notfound;
dbms_output.put_line ('Col1: '|| v_reg.col1 ||' Col2: '|| v_reg.col2);
end loop;
close cur;
end;
REF CURSOR
[editar]También se pueden definir cursores variables, a diferencia de los estáticos utilizados hasta ahora:
declare
type t_cursor is ref cursor return tabla%rowtype;
v_cursor t_cursor;
v_reg tabla%rowtype;
begin
open v_cursor for
select col1, col2
from tabla;
loop
fetch v_cursor into v_reg;
exit when v_cursor%notfound;
dbms_output.put_line ('Col1: '|| v_reg.col1 ||' Col2: '|| v_reg.col2);
end loop;
close v_cursor;
end;
Los cursores variables pueden ser pasados como parámetros en procedimientos y funciones.
También es posible no especificar el tipo de registro retornado por el cursor, lo cual permite mayor flexiblidad pero impide verificar los tipos en tiempo de compilación, lo cual puede dar lugar a errores imprevistos en tiempo de ejecución.