CREATE OR REPLACE FUNCTION food600.maz_odpocet(
	mpz2 character varying,
	mcstredisk integer,
	mcdata integer)
    RETURNS integer
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE
AS $BODY$
DECLARE doklady CURSOR FOR SELECT c_dokl FROM food600.doklady WHERE pz2=mpz2 AND c_data=mcdata AND c_stredisk=mcstredisk AND operace='VK';
	mcdokl INTEGER;
	mdone INTEGER DEFAULT 0;
	midman CHARACTER VARYING;
	mcuzaverka INTEGER;
BEGIN
SELECT id INTO midman FROM food600.food_dat WHERE c_stredisk=mcstredisk AND c_data=mcdata;
OPEN doklady;
WHILE mdone=0 LOOP
	FETCH doklady INTO mcdokl;
	IF mcdokl IS NULL THEN
		mdone:=1;
	ELSE
		DELETE FROM food600.obraty WHERE c_dokl=mcdokl AND c_data=mcdata;
		DELETE FROM food600.doklady WHERE c_dokl=mcdokl AND c_data=mcdata;
		DELETE FROM food600.dluhy WHERE c_dokl=mcdokl AND c_data=mcdata;
	END IF;
END LOOP;
IF POSITION('*' in mpz2)>0 THEN
	SELECT c_uzaverka INTO mcuzaverka FROM food600.sk__sez WHERE SUBSTR(uzaverka,3,12)||'/'||id_kas=mpz2 AND c_data=mcdata AND id_man=midman;
	DELETE FROM food600.sk__pol WHERE c_uzaverka=mcuzaverka AND c_data=mcdata;
	DELETE FROM food600.sk__fin WHERE c_uzaverka=mcuzaverka AND c_data=mcdata;
	DELETE FROM food600.sk__plt WHERE c_uzaverka=mcuzaverka AND c_data=mcdata;
	DELETE FROM food600.sk__txt WHERE c_uzaverka=mcuzaverka AND c_data=mcdata;
	DELETE FROM food600.sk__sez WHERE c_uzaverka=mcuzaverka AND c_data=mcdata;
	DELETE FROM food600.sk__uza WHERE idriadok=mcuzaverka AND c_data=mcdata;
ELSE
	UPDATE food600.sk__sez set odecteno=0 WHERE SUBSTR(uzaverka,3,12)||'/'||id_kas=mpz2 AND c_data=mcdata AND id_man=midman;
END IF;
RETURN 1;
END
$BODY$;
