MySQL自定义函数计算年龄

DROP FUNCTION countage;
DELIMITER //
CREATE FUNCTION countage(birthday VARCHAR(15)) //参数birthday 为日期格式
RETURNS INT(10)
LANGUAGE SQL DETERMINISTIC NO SQL SQL SECURITY DEFINER
BEGIN
DECLARE age INT(10);
IF birthday IS NULL THEN 
RETURN '';
END IF;
SET age = YEAR(CURDATE()) - YEAR(birthday) - 1;
IF MONTH(CURDATE()) = MONTH(birthday) THEN
IF DAY(CURDATE()) > DAY(birthday) THEN 
SET age = age + 1;
END IF;
ELSEIF MONTH(CURDATE()) > MONTH(birthday) THEN
SET age = age +1;
END IF;
RETURN age;
END//
DELIMITER ;

你可能感兴趣的:(MySQL)