Monday, October 03, 2005

Addition to my Locate IP addresses article

This refers to my article Locate IP addresses and to Arjen's article Storing an IP address in a database table to show you, how the function getCountry can be written more efficiently:
DELIMITER $$

DROP FUNCTION IF EXISTS `getCountry`$$
CREATE FUNCTION `getCountry`(pIp CHAR(16)) RETURNS varchar(100)
BEGIN
DECLARE _ip_value INT UNSIGNED;
DECLARE _country VARCHAR(100);

SELECT INET_ATON(pIp) INTO _ip_value;

SELECT b.country
FROM ip_ranges a INNER JOIN ip_countries b
ON a.code = b.code
WHERE ip_from <= _ip_value AND
ip_to >= _ip_value
INTO _country;

RETURN _country;

END$$

DELIMITER ;

No comments: