DROP FUNCTION IF EXISTS fn_GetAmbulanceEvent;
CREATE FUNCTION fn_GetAmbulanceEvent("RegisterItemID" uuid)
  RETURNS uuid AS
$BODY$
declare _event uuid;
Begin
	_event := (SELECT t0.AmbulanceEvent	FROM AKUZ.T_REGISTER_ITEM t JOIN AKUZ.T_VISIT t0 ON t.Visit = t0.VisitID WHERE t.RegisterItemID = "RegisterItemID");
	if _event is not null
	then
		return _event;
	else
		return (SELECT t1.AmbulanceEvent FROM AKUZ.T_REGISTER_ITEM t JOIN AKUZ.T_AMBULANCE_CARD_RECORD t1 ON t1.MedicalRecordID = t.Service WHERE t.RegisterItemID = "RegisterItemID");
	end if;
END $BODY$
  LANGUAGE plpgsql STABLE
  COST 100;
ALTER FUNCTION fn_GetAmbulanceEvent(uuid)
  OWNER TO postgres;
