MySQL 存储函数的正确 if 子句语法是什么?

What is the proper if clause syntax for a MySQL stored function?

我是 MySQL 的新手,所以如果其中一些相对初级,我深表歉意。

我正在尝试编写一个存储函数来将数字四舍五入到一定数量的有效数字。我有一个理论上应该可以工作的函数——我咨询了另一个有用的 Whosebug 来确定逻辑 (Round to n Significant Figures in SQL)。但是,1 和 -1 之间的数字(不包括 0,因为我加入了边缘情况)无法正确舍入;例如,调用 sfround(.00123456789, 5) 应该产生 0.0012345,而不是产生 0.0012345999712124467。

为了解决这个问题,我希望将 1 和 -1(不包括 0)之间的数字截断为平凡零的数量加上必要的 sig figs 的数量。在下面的代码中,IF 子句旨在执行此截断。但是,我发现每当我包含此 IF 子句时,都会导致错误:

'Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DECLARE numDigits INT; SET numDigits = FLOOR(LOG10(ABS(number))); #total d' at line 5).

即使我尝试使用非常简单的 IF 语句,例如

IF (5 = 5) THEN DECLARE dummyvar INT; END IF;

我在这一行仍然遇到同样的错误,这让我认为我在 IF 子句的 MySQL 语法中遗漏了一些简单的东西。

DELIMITER $$

USE `vg_summary1`$$

DROP FUNCTION IF EXISTS `sfround`$$

CREATE FUNCTION 'sfround`(number FLOAT, sf INT) RETURNS FLOAT
DETERMINISTIC
BEGIN
     IF ((ABS(number) < 1) AND (ABS(number) > 0)) THEN            
        DECLARE numDigits INT;
        SET numDigits = FLOOR(LOG10(ABS(number)));     
        DECLARE trivialDigits INT;
        SET trivialDigits = 0;                         
                DECLARE placeholder FLOAT;
        SET placeholder = ABS(number);               

        WHILE placeholder < 1
        BEGIN
           placeholder = placeholder * 10;
           IF (placeholder < 1) THEN trivialDigits = trivialDigits + 1;    
           END IF;
        END;

        DECLARE keptDigits = trivialDigits + sf;

        DECLARE special_answer FLOAT;
        SET special_answer = ROUND(number, keptDigits-1-FLOOR(LOG10(ABS(number))));
        RETURN special_answer;

     END IF;

     DECLARE r FLOAT;

     SET r = CASE WHEN number = 0 THEN 0 ELSE ROUND(number, sf-1-FLOOR(LOG10(ABS(number)))) END;
     RETURN r;

   END$$

 DELIMITER ;

如果有人对语法错误或修复原始错误的更合乎逻辑的方法有任何建议,我将不胜感激!非常感谢!

https://dev.mysql.com/doc/refman/8.0/en/declare.html

DECLARE is permitted only inside a BEGIN ... END compound statement and must be at its start, before any other statements.