DROP FUNCTION IF EXISTS fn_GetDaysForPay;
CREATE FUNCTION fn_GetDaysForPay
(
	"MesID" uuid
,	"FactDays" integer
)
RETURNS integer 
AS
$BODY$
Begin
	return 
	(
		select
			case when m.Period = 0 then "FactDays"
			     when cast("FactDays" as decimal(10,1)) / cast(m.Period as decimal(10,1)) < 0.8 then "FactDays"
			     else m.Period 
			end
		from akuz.T_MES m
		where m.MesID = "MesID"
	);
END $BODY$
  LANGUAGE plpgsql STABLE
  COST 100;
ALTER FUNCTION fn_GetDaysForPay(uuid, integer)
  OWNER TO postgres;