CREATE OR REPLACE FUNCTION food600.inventura_buranie(
	mmeno character varying,
	cdata integer,
	mmenaakt integer,
	mcstredisk integer)
    RETURNS integer
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE
AS $BODY$
DECLARE mbourskup CHARACTER(2);
	mporadi INTEGER;
	mc_karty INTEGER;
	mmnozstvi numeric(20,10);
	pocetriadkov INTEGER DEFAULT 100000;
	done INTEGER DEFAULT 0;
	pokracovat INTEGER;
	buff_2 CURSOR FOR SELECT buffer.poradi, bourak.c_karty2 as c_karty, ROUND(CAST ((buffer.mnozstvi * bourak.koef_mnoz) AS NUMERIC), 4) AS mnozstvi FROM food600.buffer LEFT JOIN food600.bourak ON bourak.c_karty = buffer.c_karty AND bourak.c_data=buffer.c_data WHERE buffer.mnozstvi > 0 AND buffer.serial_no='** BOUR **' AND bourak.bour_skup = mbourskup AND buffer.menobuf=mmeno AND buffer.c_data=cdata;
	BEGIN
SELECT bour_skup INTO mbourskup FROM food600.food_dat WHERE c_stredisk=mcstredisk;
OPEN buff_2;
WHILE (done<pocetriadkov) LOOP
	done:=done+1;
	FETCH buff_2 INTO mporadi, mc_karty, mmnozstvi;
	IF mc_karty IS NULL THEN
		pokracovat:=0;
		IF mporadi IS NULL AND mmnozstvi IS NULL THEN
			pocetriadkov:=0;
		END IF;
		
	ELSE
		pokracovat:=1;
	END IF;
	IF pokracovat=1 THEN
		SELECT COUNT(*) INTO pokracovat FROM food600.buffer WHERE c_data=cdata AND menobuf=mmeno AND c_karty=mc_karty LIMIT 1;
		IF pokracovat>0 THEN
			DELETE FROM food600.buffer WHERE menobuf=mmeno AND c_data=cdata AND poradi=mporadi;
			UPDATE food600.buffer SET mnozstvi=mnozstvi+mmnozstvi WHERE menobuf=mmeno AND c_data=cdata AND c_karty=mc_karty; 
		END IF;
	END IF;
END LOOP;
RETURN 1;
END
$BODY$;
