Así lo hago yo con un ciclo FOR
Código SQL:
Ver originalCREATE OR REPLACE FUNCTION fechas(V_IDVehiculo INTEGER) RETURNS text AS $BODY$
DECLARE
OrdenSgte INTEGER = 0;
V_TAREASGTE INTEGER = 0;
V_Fech_final TIMESTAMP WITHOUT TIME ZONE;
V_ROW_DATA TAREAS%ROWTYPE; --Va un simbolo de porcentaje entremedio de TAREAS y ROWTYPE
BEGIN
FOR V_ROW_DATA IN SELECT * FROM TAREAS WHERE ID_VEHICULO = V_IDVehiculo ORDER BY ID_TAREA LOOP
SELECT INTO V_Fech_final FECHA_FINALIZACION FROM TAREAS WHERE ID_TAREA = V_ROW_DATA.ID_TAREA;
IF V_Fech_final IS NOT NULL THEN
SELECT INTO OrdenSgte (orden + 1) FROM tareas WHERE id_tarea = V_ROW_DATA.ID_TAREA;
SELECT INTO V_TAREASGTE ID_TAREA FROM TAREAS WHERE ORDEN = OrdenSgte AND ID_VEHICULO = V_IDVehiculo;
IF V_TAREASGTE IS NOT NULL THEN
UPDATE TAREAS SET FECHA_REAL_INICIO = V_Fech_final WHERE ID_TAREA = V_TAREASGTE;
END IF;
END IF;
END LOOP;
END;
$_$
LANGUAGE plpgsql;