DATE_ADD和INTERVAL函数中的语法错误

时间:2014-07-05 01:06:53

标签: mysql function date

鉴于此功能:

DROP FUNCTION IF EXISTS expiration_date;
DELIMITER $$
CREATE FUNCTION expiration_date(lic_class VARCHAR(2), born_on DATE, at DATE) RETURNS DATE
BEGIN
    DECLARE age INTEGER;
    DECLARE span INTEGER DEFAULT 0;
    SET age = YEAR(at) - YEAR(born_on);
    IF     age < 50                 THEN SET span = 10;
    ELSEIF age >= 50 AND age < 70   THEN SET span = 5;
    ELSEIF age >= 70 AND age < 80   THEN SET span = 3;
    ELSEIF age >= 80                THEN SET span = 2;
    END IF;

    DECLARE ret DATE;
    SET ret = DATE_ADD(at, INTERVAL span YEAR); 
    RETURN ret;
END $$
DELIMITER ;
它给了我:

  

#1064 - 您的SQL语法出错;检查与您的MySQL服务器版本对应的手册,以便在“DECLARE ret DATE”附近使用正确的语法;       SET ret = DATE_ADD(at,INTERVAL span YEAR);       RETURN&#39;在第12行

为什么?我错过了什么?

1 个答案:

答案 0 :(得分:3)

根据to the DECLARE documentation

  

DECLARE仅允许在BEGIN ... END复合语句中使用,并且必须在其开始之前,在任何其他语句之前。

因此,在DECLARE ret DATE;块之后放置IF...ELSE无效。使用其他DECLARE声明将其移至顶部。

DROP FUNCTION IF EXISTS expiration_date;
DELIMITER $$
CREATE FUNCTION expiration_date(lic_class VARCHAR(2), born_on DATE, at DATE) RETURNS DATE
BEGIN
    DECLARE age INTEGER;
    DECLARE span INTEGER DEFAULT 0;
    -- No reason not to DECLARE up here!
    DECLARE ret DATE;

    SET age = YEAR(at) - YEAR(born_on);
    IF     age < 50                 THEN SET span = 10;
    ELSEIF age >= 50 AND age < 70   THEN SET span = 5;
    ELSEIF age >= 70 AND age < 80   THEN SET span = 3;
    ELSEIF age >= 80                THEN SET span = 2;
    END IF;

    SET ret = DATE_ADD(at, INTERVAL span YEAR); 
    RETURN ret;
END $$
DELIMITER ;