MySQL select 使用 if then else 方法将一条记录写入函数内部的变量

MySQL select one record into variable inside of the function using if then else approach

我正在尝试构建一个 mysql 函数,在给定输入变量的情况下,该函数能够进入其中一个 if 分支并使用 select 设置一个变量。然后应该返回这个变量。浏览了一堆手册后,我确定了以下代码:

create function dayssincelastmo(sedol varchar(255), currDate datetime, z_score double, groupnum int)
returns int
deterministic 
begin
    if zscore<0 then
        select datediff(p.`Period (Formatted)`, currDate) into @days
            from
                price as p
            where
                p.G_SEDOL = sedol
                and p.`Period (Formatted)`<=currDate
                and p.zscore<=z_score
                and p.`GRP MODEL NUM` = groupnum
                order by p.`Period (Formatted)`
                limit 1;
    end if;
    if zscore>=0 then
        select datediff(p.`Period (Formatted)`, currDate)  into @days
            from
                price as p
            where
                p.G_SEDOL = sedol
                and p.`Period (Formatted)`<=currDate
                and p.zscore>=z_score
                and p.`GRP MODEL NUM` = groupnum
                order by p.`Period (Formatted)`
                limit 1;
    end if;
return @days
end

如您所见,我将输出数量限制为 1,以便在每个分支中仅从 select 中获取一个值。我还使用 if then else 方法并用 end if.

关闭我的每个 if 语句

但是我在第 15 行的解释器中得到一个错误,它恰好有极限 1;条目:

order by p.`Period (Formatted)`
**limit 1;**

有什么错误的建议吗?

不要忘记 RETURN 语句中的分号 (;):

...
-- return @days
return @days;
...

更新

我无法重现问题:

mysql> DROP FUNCTION IF EXISTS `dayssincelastmo`;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> DELIMITER //

mysql> create function dayssincelastmo(
    ->   sedol varchar(255),
    ->   currDate datetime,
    ->   z_score double,
    ->   groupnum int
    -> )
    -> returns int
    -> deterministic 
    -> begin
    ->     if zscore<0 then
    ->         select datediff(p.`Period (Formatted)`, currDate) into @days
    ->             from
    ->                 price as p
    ->             where
    ->                 p.G_SEDOL = sedol
    ->                 and p.`Period (Formatted)`<=currDate
    ->                 and p.zscore<=z_score
    ->                 and p.`GRP MODEL NUM` = groupnum
    ->                 order by p.`Period (Formatted)`
    ->                 limit 1;
    ->     end if;
    ->     if zscore>=0 then
    ->         select datediff(p.`Period (Formatted)`, currDate)  into @days
    ->             from
    ->                 price as p
    ->             where
    ->                 p.G_SEDOL = sedol
    ->                 and p.`Period (Formatted)`<=currDate
    ->                 and p.zscore>=z_score
    ->                 and p.`GRP MODEL NUM` = groupnum
    ->                 order by p.`Period (Formatted)`
    ->                 limit 1;
    ->     end if;
    -> return @days;
    -> end//
Query OK, 0 rows affected (0.01 sec)

mysql> DELIMITER ;