CREATE OR REPLACE FUNCTION food600.maz_polotovary_novy(
	mcdokl integer,
	mcdata integer,
	mcstredisk integer)
    RETURNS integer
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE
AS $BODY$

DECLARE 
	karty CURSOR FOR SELECT DISTINCT c_karty FROM food600.obraty WHERE c_dokl=mcdokl;
	mdone INTEGER DEFAULT 0;
	mporadi INTEGER;
	mckarty INTEGER;
BEGIN
OPEN karty;
mdone:=10100;
WHILE (mdone>0) LOOP
	FETCH karty INTO mckarty;
	IF mckarty ISNULL THEN
		mdone:=0;
	ELSE
		SELECT MIN(poradi) INTO mporadi FROM food600.obraty WHERE c_karty=mckarty AND c_stredisk=mcstredisk AND c_dokl=mcdokl;
		UPDATE food600.obraty SET dan=9 WHERE c_karty=mckarty AND c_stredisk=mcstredisk AND c_dokl=mcdokl AND poradi<>mporadi;
	END IF;
END LOOP;
CLOSE karty;
DELETE FROM food600.obraty WHERE c_dokl=mcdokl AND c_data=mcdata AND dan=9;
RETURN 1;
END
$BODY$;
