DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`address_getGeo`(vSelf INT) RETURNS int(11) DETERMINISTIC BEGIN /** * Returns the geo for the passed address. * * @param vSelf The address id * @return The geo id */ DECLARE vGeoFk INT; SELECT p.geoFk INTO vGeoFk FROM address a JOIN town t ON t.provinceFk = a.provinceFk JOIN postCode p ON p.townFk = t.id AND (p.code = a.postalCode OR a.postalCode IS NULL) JOIN zoneGeo zg ON zg.id = p.geoFk WHERE a.id = vSelf ORDER BY (a.city SOUNDS LIKE t.name) DESC, (p.code = a.postalCode) DESC LIMIT 1; RETURN vGeoFk; END$$ DELIMITER ;