DROP FUNCTION IF EXISTS fn_GetRegistration;
CREATE FUNCTION fn_GetRegistration
(
	"PatientID" uuid
,	"OnDate" timestamp
,	"Profile" integer
)
RETURNS uuid AS
$BODY$	
Begin
	return
	(
		select r.RegistrationID 
		from akuz.T_REGISTRATION r
		where r.Patient = "PatientID" 
		and r.RegistrationDate <= Coalesce("OnDate", Current_TimeStamp::TIMESTAMP) 
		and r.AttachmentStatus > 0
		AND r.Profile >= case when coalesce("Profile", 2) = 2 then 1 else "Profile" end
		AND r.Profile <= case when coalesce("Profile", 1) = 1 then 2 else "Profile" end
		order by r.RegistrationDate desc		
		Limit 1
	);
END $BODY$
  LANGUAGE plpgsql volatile
  COST 100;
ALTER FUNCTION fn_getregistration(uuid, timestamp, integer)
  OWNER TO postgres;
