CREATE OR REPLACE FUNCTION food600.prepocetalergenov(
	mckarty integer,
	mcdata integer)
    RETURNS integer
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE
AS $BODY$
DECLARE 
	mckarty2 INTEGER;
	zoznamkalk CURSOR FOR SELECT DISTINCT c_karty as c_karty from food600.polozky WHERE c_poloz=mckarty and c_data=mcdata;
	zoznampol CURSOR FOR SELECT DISTINCT krest.alergeny as alergeny from food600.krest LEFT JOIN food600.polozky ON krest.c_karty=polozky.c_poloz and krest.c_data=polozky.c_data where polozky.c_karty=mckarty2 and polozky.c_data=mcdata AND krest.alergeny>0;
	alergen INTEGER DEFAULT 0;
	alergenn INTEGER DEFAULT 0;
	mdone INTEGER DEFAULT 1;
	mdone1 INTEGER DEFAULT 1;
	idr INTEGER;
BEGIN

OPEN zoznamkalk;
WHILE (mdone>0) LOOP
	FETCH zoznamkalk INTO mckarty2;
	IF mckarty2 ISNULL THEN
		mdone:=0;
	ELSE
		alergen:=0;
		OPEN zoznampol;
		WHILE (mdone1>0) LOOP
			FETCH zoznampol INTO alergenn;
			IF alergenn IS NULL THEN
				mdone1:=0;
			ELSE
				alergen:=CAST(CAST(alergen AS BIT(20))|CAST(alergenn AS BIT(20)) AS INTEGER);
			END IF;
			IF mdone1=0 THEN
				SELECT idriadok INTO idr FROM food600.krest WHERE c_data=mcdata AND c_karty=mckarty2;
				IF idr IS NULL THEN
					INSERT INTO food600.krest (c_karty, alergeny, c_data) VALUES (mckarty2, alergen, mcdata);
				ELSE
					UPDATE food600.krest SET alergeny=alergen WHERE idriadok=idr;
				END IF;
				
--				PERFORM food600.prepocetalergenov(mckarty2,mcdata);
			END IF;
		END LOOP;
		CLOSE zoznampol;
	END IF;
END LOOP;
CLOSE zoznamkalk;
RETURN 1;
END
$BODY$;
