DROP FUNCTION IF EXISTS fn_GetProgramItemRate;
CREATE FUNCTION fn_GetProgramItemRate
(
	"WarrantyProgramItemID" uuid
,	"OnDate" timestamp without time zone
)
RETURNS uuid AS
$BODY$
Begin
	if "OnDate" is null 
	then "OnDate" := Current_Timestamp::TIMESTAMP;
	end if;
	
	return
	(
		select w.WarrantyProgramItemRateID 
		from AKUZ.T_WARRANTY_PROGRAM_ITEM_RATE w
		where w.WarrantyProgramItem = "WarrantyProgramItemID"
		and Date_Part('day', w.EffectiveDate - "OnDate") >= 0
		order by w.EffectiveDate desc
		Limit 1
	);
END $BODY$
  LANGUAGE plpgsql STABLE
  COST 100;
ALTER FUNCTION fn_GetProgramItemRate(uuid, timestamp without time zone)
  OWNER TO postgres;