CREATE OR REPLACE FUNCTION fill_temp_tetel_rendeles(param_tetel_kod integer, param_raktar_kod integer)
  RETURNS integer AS
'declare

tetel_rendeles cursor for

select partner_kod, rendelt
  from tetel_rendeles
  where tetel_kod = param_tetel_kod
    and raktar_kod = param_raktar_kod
 order by partner_kod;

Query              refcursor;
data_partner_kod   integer;
data_lekerdezes    integer;
data_rendelt       numeric;
query_telj_datum   date;
query_mennyiseg    numeric;

begin
  data_lekerdezes := null_to_zero((SELECT max(lekerdezes) FROM _temp_tetel_rendeles)) + 1;
  open tetel_rendeles;

  fetch tetel_rendeles
   into data_partner_kod,data_rendelt;

  while found loop

        OPEN Query FOR

		SELECT raktar_mozgas_fej.telj_datum, raktar_mozgas.mennyiseg 
		FROM raktar_mozgas_fej
		INNER JOIN raktar_mozgas ON raktar_mozgas_fej.kod = raktar_mozgas.fej_kod
		WHERE raktar_mozgas_fej.bizonylat_fajta = 11
		AND raktar_mozgas.tetel_kod = param_tetel_kod
		AND raktar_mozgas.forras_raktar_kod = param_raktar_kod
		AND raktar_mozgas_fej.partner_kod = data_partner_kod		
		ORDER BY telj_datum DESC;

	FETCH Query INTO query_telj_datum, query_mennyiseg;
	if query_mennyiseg > data_rendelt then
	   query_mennyiseg := data_rendelt;
	   data_rendelt := 0;
	else
	   data_rendelt := data_rendelt - query_mennyiseg;
	end if;

	WHILE FOUND LOOP


            INSERT INTO _temp_tetel_rendeles (lekerdezes, datum, partner_kod, mennyiseg)
                  VALUES (data_lekerdezes, query_telj_datum, data_partner_kod, query_mennyiseg);

            FETCH Query INTO query_telj_datum, query_mennyiseg;
	    if query_mennyiseg > data_rendelt then
	       query_mennyiseg := data_rendelt;
	       data_rendelt := 0;
	    else
	       data_rendelt := data_rendelt - query_mennyiseg;
	end if;            
	END LOOP;

	CLOSE Query;	

      fetch tetel_rendeles
        into data_partner_kod,data_rendelt;
  end loop;

  close tetel_rendeles;

  return data_lekerdezes;
end;'
  LANGUAGE plpgsql VOLATILE
  COST 100;